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

CREATE OR REPLACE FUNCTION public.rpc_admin_user_bill_list(
    p_page INTEGER DEFAULT 1,
    p_page_size INTEGER DEFAULT 15,
    p_category VARCHAR DEFAULT NULL,
    p_type VARCHAR DEFAULT NULL,
    p_pm 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_bill b
    LEFT JOIN public.ak_users u ON u.id = b.uid
    WHERE (p_category IS NULL OR b.category = p_category)
      AND (p_type IS NULL OR b.type = p_type)
      AND (p_pm IS NULL OR b.pm = p_pm)
      AND (p_start_time IS NULL OR b.created_at >= p_start_time)
      AND (p_end_time IS NULL OR b.created_at <= p_end_time)
      AND (p_search IS NULL OR (
          COALESCE(b.title, '') 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 
            b.id,
            b.uid,
            b.link_id,
            b.pm,
            b.title,
            b.category,
            b.type,
            b.number,
            b.balance,
            b.mark,
            b.status,
            b.created_at,
            b.updated_at,
            u.username as user_name,
            u.email as user_email
        FROM public.ml_user_bill b
        LEFT JOIN public.ak_users u ON u.id = b.uid
        WHERE (p_category IS NULL OR b.category = p_category)
          AND (p_type IS NULL OR b.type = p_type)
          AND (p_pm IS NULL OR b.pm = p_pm)
          AND (p_start_time IS NULL OR b.created_at >= p_start_time)
          AND (p_end_time IS NULL OR b.created_at <= p_end_time)
          AND (p_search IS NULL OR (
              COALESCE(b.title, '') ILIKE '%' || p_search || '%' OR
              COALESCE(u.username, '') ILIKE '%' || p_search || '%' OR
              COALESCE(u.email, '') ILIKE '%' || p_search || '%'
          ))
        ORDER BY b.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_user_bill_list IS '管理员资金流水列表分页查询';
