-- =====================================================================================
-- Admin 财务功能 - 财务概况统计 RPC
-- 位置：docs/sql/30_rpc/finance/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：获取指定时间段内的财务核心 KPI（营业额、充值汇总、提现汇总、资金存量）
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_finance_overview(
    p_start_time TIMESTAMP WITH TIME ZONE,
    p_end_time TIMESTAMP WITH TIME ZONE
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_recharge_amount DECIMAL(12,2);
    v_recharge_count BIGINT;
    v_extract_amount DECIMAL(12,2);
    v_extract_count BIGINT;
    v_total_user_balance DECIMAL(12,2);
    v_total_user_brokerage DECIMAL(12,2);
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 统计充值 (仅统计已支付)
    SELECT 
        COALESCE(SUM(price + give_price), 0),
        COUNT(*)
    INTO v_recharge_amount, v_recharge_count
    FROM public.ml_user_recharge
    WHERE paid = 1
      AND created_at >= p_start_time
      AND created_at <= p_end_time;

    -- 3. 统计提现 (仅统计已通过)
    SELECT 
        COALESCE(SUM(extract_price), 0),
        COUNT(*)
    INTO v_extract_amount, v_extract_count
    FROM public.ml_extract
    WHERE status = 1
      AND created_at >= p_start_time
      AND created_at <= p_end_time;

    -- 4. 统计全站资金存量 (实时快照)
    SELECT 
        COALESCE(SUM(now_money), 0),
        COALESCE(SUM(brokerage_price), 0)
    INTO v_total_user_balance, v_total_user_brokerage
    FROM public.ak_users;

    RETURN jsonb_build_object(
        'recharge_amount', v_recharge_amount,
        'recharge_count', v_recharge_count,
        'extract_amount', v_extract_amount,
        'extract_count', v_extract_count,
        'total_user_balance', v_total_user_balance,
        'total_user_brokerage', v_total_user_brokerage
    );
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_finance_overview IS '财务核心 KPI 概况统计';
