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

CREATE OR REPLACE FUNCTION public.rpc_admin_kefu_word_save(
    p_id UUID DEFAULT NULL,
    p_category_id UUID DEFAULT NULL,
    p_title TEXT DEFAULT NULL,
    p_content 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_category_id IS NULL OR p_title IS NULL OR p_content IS NULL THEN
            RAISE EXCEPTION 'Missing required fields';
        END IF;

        INSERT INTO public.ml_kefu_words (
            category_id, title, content, sort
        ) VALUES (
            p_category_id, p_title, p_content, p_sort
        ) RETURNING id INTO v_id;
    ELSE
        -- 3. 更新
        UPDATE public.ml_kefu_words
        SET 
            category_id = COALESCE(p_category_id, category_id),
            title = COALESCE(p_title, title),
            content = COALESCE(p_content, content),
            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 'Word not found';
        END IF;
    END IF;

    RETURN v_id;
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_kefu_word_save IS '管理员新增或更新快捷话术';
