-- =====================================================================================
-- RPC: rpc_admin_kefu_word_list
-- 位置：docs/sql/30_rpc/kefu/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端获取指定分类下的快捷话术列表
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_kefu_word_list(
    p_category_id UUID DEFAULT NULL,
    p_search TEXT DEFAULT NULL
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_items JSONB;
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. 获取话术列表
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            w.id, 
            w.category_id, 
            w.title, 
            w.content, 
            w.sort, 
            w.created_at, 
            w.updated_at,
            c.name as category_name
        FROM public.ml_kefu_words w
        JOIN public.ml_kefu_word_categories c ON c.id = w.category_id
        WHERE (p_category_id IS NULL OR w.category_id = p_category_id)
          AND (p_search IS NULL OR w.title ILIKE '%' || p_search || '%' OR w.content ILIKE '%' || p_search || '%')
        ORDER BY w.sort ASC, w.created_at DESC
    ) t;

    RETURN COALESCE(v_items, '[]'::jsonb);
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_kefu_word_list IS '管理员获取快捷话术列表';
