-- =====================================================================================
-- Admin 财务统计 - 余额收支分布统计 RPC
-- 位置：docs/sql/30_rpc/finance/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：按业务子类型统计指定时间范围内的余额收入与支出分布
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_balance_distribution(
    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_total_income DECIMAL(12,2);
    v_total_expense DECIMAL(12,2);
    v_income_items JSONB;
    v_expense_items JSONB;
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(number) FILTER (WHERE pm = 1), 0),
        COALESCE(SUM(number) FILTER (WHERE pm = 0), 0)
    INTO v_total_income, v_total_expense
    FROM public.ml_user_bill
    WHERE category = 'balance' 
      AND created_at >= p_start_time 
      AND created_at <= p_end_time
      AND status = 1;

    -- 3. 统计收入分布 (来源分析)
    SELECT jsonb_agg(t) INTO v_income_items
    FROM (
        SELECT 
            type AS name,
            SUM(number) AS value,
            CASE WHEN v_total_income > 0 THEN ROUND(SUM(number) / v_total_income * 100, 2) ELSE 0 END AS percent
        FROM public.ml_user_bill
        WHERE category = 'balance' AND pm = 1 AND status = 1
          AND created_at >= p_start_time AND created_at <= p_end_time
        GROUP BY type
        ORDER BY value DESC
    ) t;

    -- 4. 统计支出分布 (消耗分析)
    SELECT jsonb_agg(t) INTO v_expense_items
    FROM (
        SELECT 
            type AS name,
            SUM(number) AS value,
            CASE WHEN v_total_expense > 0 THEN ROUND(SUM(number) / v_total_expense * 100, 2) ELSE 0 END AS percent
        FROM public.ml_user_bill
        WHERE category = 'balance' AND pm = 0 AND status = 1
          AND created_at >= p_start_time AND created_at <= p_end_time
        GROUP BY type
        ORDER BY value DESC
    ) t;

    RETURN jsonb_build_object(
        'income', COALESCE(v_income_items, '[]'::jsonb),
        'expense', COALESCE(v_expense_items, '[]'::jsonb)
    );
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_balance_distribution IS '统计财务余额收支来源与消耗分布';
