-- =====================================================================================
-- Admin 财务功能 - 充值记录列表分页查询 RPC
-- 位置：docs/sql/30_rpc/finance/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 依赖：ml_user_recharge, ak_users 表已存在
-- 权限：仅 admin 角色可执行（口径 A：全局数据访问通过 RPC）
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_recharge_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_paid SMALLINT DEFAULT NULL,
    p_start_time TIMESTAMP WITH TIME ZONE DEFAULT NULL,
    p_end_time TIMESTAMP WITH TIME ZONE 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 id = auth.uid() AND role = 'admin'
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    v_offset := (p_page - 1) * p_page_size;

    -- 2. 获取总数
    SELECT COUNT(*) INTO v_total
    FROM public.ml_user_recharge r
    LEFT JOIN public.ak_users u ON u.id = r.uid
    WHERE (p_paid IS NULL OR r.paid = p_paid)
      AND (p_start_time IS NULL OR r.created_at >= p_start_time)
      AND (p_end_time IS NULL OR r.created_at <= p_end_time)
      AND (p_search IS NULL OR (
          COALESCE(r.order_no, '') ILIKE '%' || p_search || '%' OR
          COALESCE(u.username, '') ILIKE '%' || p_search || '%' OR
          COALESCE(u.email, '') ILIKE '%' || p_search || '%'
      ));

    -- 3. 获取明细数据
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT 
            r.id,
            r.uid,
            r.order_no,
            r.recharge_type,
            r.price,
            r.give_price,
            r.paid,
            r.pay_time,
            r.channel_trade_no,
            r.status,
            r.created_at,
            r.updated_at,
            u.username as user_name,
            u.email as user_email
        FROM public.ml_user_recharge r
        LEFT JOIN public.ak_users u ON u.id = r.uid
        WHERE (p_paid IS NULL OR r.paid = p_paid)
          AND (p_start_time IS NULL OR r.created_at >= p_start_time)
          AND (p_end_time IS NULL OR r.created_at <= p_end_time)
          AND (p_search IS NULL OR (
              COALESCE(r.order_no, '') ILIKE '%' || p_search || '%' OR
              COALESCE(u.username, '') ILIKE '%' || p_search || '%' OR
              COALESCE(u.email, '') ILIKE '%' || p_search || '%'
          ))
        ORDER BY r.created_at DESC
        LIMIT p_page_size
        OFFSET v_offset
    ) t;

    -- 4. 返回结果
    RETURN jsonb_build_object(
        'total', v_total,
        'items', COALESCE(v_items, '[]'::jsonb)
    );
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_recharge_list IS '管理员充值记录列表分页查询';
