-- =====================================================================================
-- RPC: rpc_admin_article_list
-- 位置：docs/sql/30_rpc/cms/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端分页获取文章列表，支持搜索、分类筛选及状态过滤
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_article_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_category_id UUID DEFAULT NULL,
    p_status SMALLINT DEFAULT NULL,
    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_articles a
    WHERE (p_category_id IS NULL OR a.category_id = p_category_id)
      AND (p_status IS NULL OR a.status = p_status)
      AND (p_search IS NULL OR a.title ILIKE '%' || p_search || '%' OR a.author ILIKE '%' || p_search || '%');

    -- 3. 获取列表数据
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            a.id,
            a.category_id,
            c.name as category_name,
            a.title,
            a.author,
            a.image,
            a.description,
            a.status,
            a.views,
            a.is_banner,
            a.is_hot,
            a.created_at,
            a.updated_at
        FROM public.ml_articles a
        LEFT JOIN public.ml_article_categories c ON c.id = a.category_id
        WHERE (p_category_id IS NULL OR a.category_id = p_category_id)
          AND (p_status IS NULL OR a.status = p_status)
          AND (p_search IS NULL OR a.title ILIKE '%' || p_search || '%' OR a.author ILIKE '%' || p_search || '%')
        ORDER BY a.created_at DESC
        LIMIT p_page_size
        OFFSET v_offset
    ) t;

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

COMMENT ON FUNCTION public.rpc_admin_article_list IS '管理员分页查询文章列表';
