-- =====================================================================================
-- RPC: rpc_admin_user_list
-- Version: v1
-- Purpose: 管理后台用户列表（分页+筛选），返回基础资料+会员信息+余额(0)
-- Security: SECURITY DEFINER + 固定 search_path + 入口鉴权（admin/analytics）
-- Depends:
--   - public.ak_users (auth_id, email, username, role, created_at, updated_at)
--   - public.ml_user_profiles (user_id, status, real_name, credit_score, verification_status)
--   - public.ml_user_subscriptions (user_id, plan_id, status, end_date)
--   - public.ml_subscription_plans (id, name, billing_period, price)
--   - public.get_current_user_role() (鉴权入口)
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_user_list(
    p_page INTEGER DEFAULT 1,
    p_limit INTEGER DEFAULT 20,
    p_search TEXT DEFAULT NULL,
    p_role TEXT DEFAULT NULL,
    p_status INTEGER DEFAULT NULL,
    p_is_member BOOLEAN DEFAULT NULL
)
RETURNS TABLE (
    total BIGINT,
    page INTEGER,
    page_limit INTEGER,
    has_more BOOLEAN,
    items JSONB
)
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
    v_offset INTEGER := (p_page - 1) * p_limit;
    v_total BIGINT;
    v_items JSONB;
BEGIN
    -- 1) 入口鉴权：仅允许 admin/analytics 角色调用
    IF get_current_user_role() NOT IN ('admin', 'analytics') THEN
        RAISE EXCEPTION 'Permission denied: required role admin or analytics';
    END IF;

    -- 2) 计算总数（用于分页）
    WITH filtered_users AS (
        SELECT u.id, u.auth_id, u.email, u.username, u.role,
               u.created_at, u.updated_at,
               up.status as profile_status,
               up.real_name,
               up.credit_score,
               up.verification_status
        FROM public.ak_users u
        LEFT JOIN public.ml_user_profiles up ON u.id = up.user_id
        WHERE 1=1
            AND (p_search IS NULL OR (
                u.username ILIKE '%' || p_search || '%' OR
                u.email ILIKE '%' || p_search || '%' OR
                up.real_name ILIKE '%' || p_search || '%'
            ))
            AND (p_role IS NULL OR u.role = p_role)
            AND (p_status IS NULL OR up.status = p_status)
            AND (
                p_is_member IS NULL OR
                (p_is_member = TRUE AND EXISTS (
                    SELECT 1
                    FROM public.ml_user_subscriptions s
                    WHERE s.user_id = u.auth_id
                      AND s.status IN ('trial', 'active')
                      AND (s.end_date IS NULL OR s.end_date >= now())
                )) OR
                (p_is_member = FALSE AND NOT EXISTS (
                    SELECT 1
                    FROM public.ml_user_subscriptions s
                    WHERE s.user_id = u.auth_id
                      AND s.status IN ('trial', 'active')
                      AND (s.end_date IS NULL OR s.end_date >= now())
                ))
            )
    )
    SELECT COUNT(*) INTO v_total FROM filtered_users;

    -- 3) 查询分页数据并组装会员信息
    SELECT jsonb_agg(
        jsonb_build_object(
            'id', u.id,
            'auth_id', u.auth_id,
            'username', u.username,
            'email', u.email,
            'role', u.role,
            'profile_status', u.profile_status,
            'real_name', u.real_name,
            'credit_score', u.credit_score,
            'verification_status', u.verification_status,
            'created_at', u.created_at,
            'updated_at', u.updated_at,
            'balance', 0, -- 按要求固定返回 0
            'is_member', COALESCE(member_info.is_member, false),
            'member_plan_name', member_info.plan_name,
            'member_end_date', member_info.end_date
        )
    ) INTO v_items
    FROM (
        SELECT u.*, up.status as profile_status, up.real_name, up.credit_score, up.verification_status
        FROM public.ak_users u
        LEFT JOIN public.ml_user_profiles up ON u.id = up.user_id
        WHERE 1=1
            AND (p_search IS NULL OR (
                u.username ILIKE '%' || p_search || '%' OR
                u.email ILIKE '%' || p_search || '%' OR
                up.real_name ILIKE '%' || p_search || '%'
            ))
            AND (p_role IS NULL OR u.role = p_role)
            AND (p_status IS NULL OR up.status = p_status)
            AND (
                p_is_member IS NULL OR
                (p_is_member = TRUE AND EXISTS (
                    SELECT 1
                    FROM public.ml_user_subscriptions s
                    WHERE s.user_id = u.auth_id
                      AND s.status IN ('trial', 'active')
                      AND (s.end_date IS NULL OR s.end_date >= now())
                )) OR
                (p_is_member = FALSE AND NOT EXISTS (
                    SELECT 1
                    FROM public.ml_user_subscriptions s
                    WHERE s.user_id = u.auth_id
                      AND s.status IN ('trial', 'active')
                      AND (s.end_date IS NULL OR s.end_date >= now())
                ))
            )
        ORDER BY u.created_at DESC
        LIMIT p_limit OFFSET v_offset
    ) u
    LEFT JOIN LATERAL (
        SELECT
            true as is_member,
            p.name as plan_name,
            s.end_date
        FROM public.ml_user_subscriptions s
        JOIN public.ml_subscription_plans p ON s.plan_id = p.id
        WHERE s.user_id = u.auth_id
          AND s.status IN ('trial', 'active')
          AND (s.end_date IS NULL OR s.end_date >= now())
        ORDER BY s.end_date DESC NULLS FIRST
        LIMIT 1
    ) member_info ON true;

    -- 4) 返回分页结构
    RETURN QUERY
    SELECT
        v_total,
        p_page,
        p_limit AS page_limit,
        (v_offset + p_limit) < v_total as has_more,
        COALESCE(v_items, '[]'::jsonb) as items;
END;
$$;