-- RPC: rpc_admin_get_admin_list
-- 管理端获取管理员列表
-- 筛选 ak_users 表中 role 为 'admin' 或 'analytics' 的用户，并关联显示其角色信息

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

    -- 2. 获取总数
    SELECT COUNT(*) INTO v_total
    FROM public.ak_users u
    WHERE u.role IN ('admin', 'analytics')
      AND (p_status IS NULL OR u.is_active = (p_status = 1))
      AND (p_search IS NULL OR u.username ILIKE '%' || p_search || '%' OR u.real_name ILIKE '%' || p_search || '%');

    -- 3. 获取数据列表 (关联角色)
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            u.id,
            u.username,
            u.real_name,
            u.role,
            u.is_active,
            u.last_login_at,
            u.last_login_ip,
            (
                SELECT jsonb_agg(r.name)
                FROM public.ak_admin_roles ar
                JOIN public.ak_roles r ON r.id = ar.role_id
                WHERE ar.user_id = u.id
            ) as roles
        FROM public.ak_users u
        WHERE u.role IN ('admin', 'analytics')
          AND (p_status IS NULL OR u.is_active = (p_status = 1))
          AND (p_search IS NULL OR u.username ILIKE '%' || p_search || '%' OR u.real_name ILIKE '%' || p_search || '%')
        ORDER BY u.created_at DESC
        LIMIT p_page_size OFFSET v_offset
    ) t;

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

-- 授权
REVOKE ALL ON FUNCTION public.rpc_admin_get_admin_list(TEXT, SMALLINT, INTEGER, INTEGER) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.rpc_admin_get_admin_list(TEXT, SMALLINT, INTEGER, INTEGER) TO authenticated;
