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

CREATE OR REPLACE FUNCTION public.rpc_admin_kefu_word_category_list()
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 id, name, sort, created_at, updated_at
        FROM public.ml_kefu_word_categories
        ORDER BY sort ASC, created_at DESC
    ) t;

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

COMMENT ON FUNCTION public.rpc_admin_kefu_word_category_list IS '管理员获取话术分类列表';
