-- =====================================================================================
-- RPC: rpc_admin_kefu_word_category_save
-- 位置：docs/sql/30_rpc/kefu/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端新增或更新话术分类
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_kefu_word_category_save(
    p_id UUID DEFAULT NULL,
    p_name TEXT DEFAULT NULL,
    p_sort INTEGER DEFAULT 0
)
RETURNS UUID
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_id UUID;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 新增
    IF p_id IS NULL THEN
        IF p_name IS NULL THEN
            RAISE EXCEPTION 'Missing required fields: name';
        END IF;

        INSERT INTO public.ml_kefu_word_categories (
            name, sort
        ) VALUES (
            p_name, p_sort
        ) RETURNING id INTO v_id;
    ELSE
        -- 3. 更新
        UPDATE public.ml_kefu_word_categories
        SET 
            name = COALESCE(p_name, name),
            sort = COALESCE(p_sort, sort),
            updated_at = now()
        WHERE id = p_id
        RETURNING id INTO v_id;

        IF v_id IS NULL THEN
            RAISE EXCEPTION 'Category not found';
        END IF;
    END IF;

    RETURN v_id;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_kefu_word_category_save IS '管理员新增或更新话术分类';
