-- =====================================================================================
-- RPC: rpc_admin_user_group_list
-- 位置：docs/sql/30_rpc/user/
-- 对象类型：RPC 函数 (SECURITY DEFINER)
-- 版本：v1
-- 说明：管理端分页获取用户分组列表，支持搜索、状态筛选及逻辑删除过滤
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_user_group_list(
    p_page INT,
    p_page_size INT,
    p_search TEXT DEFAULT NULL,
    p_status INT DEFAULT NULL,
    p_include_deleted BOOLEAN DEFAULT FALSE
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_total INT;
    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;

    -- 2. 获取总数
    SELECT COUNT(*) INTO v_total
    FROM public.ak_user_groups
    WHERE (p_include_deleted OR deleted_at IS NULL)
      AND (p_search IS NULL OR name ILIKE '%' || p_search || '%' OR remark ILIKE '%' || p_search || '%')
      AND (p_status IS NULL OR status = p_status);

    -- 3. 分页获取数据
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            id, name, remark, status,
            created_at, updated_at, deleted_at
        FROM public.ak_user_groups
        WHERE (p_include_deleted OR deleted_at IS NULL)
          AND (p_search IS NULL OR name ILIKE '%' || p_search || '%' OR remark ILIKE '%' || p_search || '%')
          AND (p_status IS NULL OR status = p_status)
        ORDER BY created_at DESC
        LIMIT p_page_size
        OFFSET (p_page - 1) * p_page_size
    ) t;

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