-- =====================================================================================
-- Admin 财务功能 - 账单汇总统计 RPC
-- 位置：docs/sql/30_rpc/finance/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：按日/周/月维度聚合财务收支数据，支撑账单列表展示
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_finance_bill_summary(
    p_start_time TIMESTAMP WITH TIME ZONE,
    p_end_time TIMESTAMP WITH TIME ZONE,
    p_interval TEXT DEFAULT 'day' -- day, week, month
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_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 jsonb_agg(t) INTO v_items
    FROM (
        SELECT
            to_char(date_trunc(p_interval, created_at), 
                CASE 
                    WHEN p_interval = 'day' THEN 'YYYY-MM-DD'
                    WHEN p_interval = 'week' THEN 'IYYY-IW'
                    ELSE 'YYYY-MM'
                END
            ) AS date_group,
            SUM(number) FILTER (WHERE pm = 1) AS income,
            SUM(number) FILTER (WHERE pm = 0) AS expense,
            SUM(CASE WHEN pm = 1 THEN number ELSE -number END) AS net_entry
        FROM public.ml_user_bill
        WHERE created_at >= p_start_time
          AND created_at <= p_end_time
          AND status = 1
        GROUP BY date_trunc(p_interval, created_at)
        ORDER BY date_trunc(p_interval, created_at) DESC
    ) t;

    RETURN COALESCE(v_items, '[]'::jsonb);
END;
$$;

COMMENT ON FUNCTION public.rpc_admin_finance_bill_summary IS '按周期聚合财务收支账单';
