-- =====================================================================================
-- Admin 财务统计 - 余额核心指标 RPC
-- 位置：docs/sql/30_rpc/finance/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：获取全站当前余额存量、累计增加总额及累计消耗总额
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_balance_stats()
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_current_balance DECIMAL(12,2);
    v_total_accumulation DECIMAL(12,2);
    v_total_consumption 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(now_money), 0) INTO v_current_balance FROM public.ak_users;

    -- 3. 统计累计增加 (pm=1) 和 累计消耗 (pm=0)
    -- 基于 ml_user_bill 表中 category='balance' 的记录
    SELECT 
        COALESCE(SUM(number) FILTER (WHERE pm = 1), 0),
        COALESCE(SUM(number) FILTER (WHERE pm = 0), 0)
    INTO v_total_accumulation, v_total_consumption
    FROM public.ml_user_bill
    WHERE category = 'balance' AND status = 1;

    RETURN jsonb_build_object(
        'current_balance', v_current_balance,
        'total_accumulation', v_total_accumulation,
        'total_consumption', v_total_consumption
    );
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_balance_stats IS '获取全站余额存量及累计收支汇总';
