-- =====================================================================================
-- RPC: rpc_admin_article_category_list
-- 位置：docs/sql/30_rpc/cms/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端分页获取文章分类列表
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_article_category_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_search TEXT DEFAULT NULL
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_offset INTEGER;
    v_total BIGINT;
    v_items JSONB;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE auth_id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    v_offset := (p_page - 1) * p_page_size;

    -- 2. 获取总数
    SELECT COUNT(*) INTO v_total
    FROM public.ml_article_categories
    WHERE (p_search IS NULL OR name ILIKE '%' || p_search || '%');

    -- 3. 获取列表
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT id, name, icon, sort, status, created_at, updated_at
        FROM public.ml_article_categories
        WHERE (p_search IS NULL OR name ILIKE '%' || p_search || '%')
        ORDER BY sort ASC, created_at DESC
        LIMIT p_page_size
        OFFSET v_offset
    ) t;

    RETURN jsonb_build_object(
        'total', v_total,
        'items', COALESCE(v_items, '[]'::jsonb)
    );
END;
$$;
