-- =====================================================================================
-- Admin 订单统计 - 订单来源分布 RPC
-- 位置：docs/sql/30_rpc/order/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：统计订单来源分布。
-- 注意：当前 ml_orders DDL 未包含来源/渠道字段，本函数提供最小可用兜底：统一返回 "unknown" 汇总。
--       若后续新增 channel/payment_method 等字段，可在此函数中替换为按渠道分组统计。
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_order_source_stats(
    p_start_time TIMESTAMPTZ,
    p_end_time TIMESTAMPTZ
)
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 auth_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
            CASE o.channel_type
                WHEN 1 THEN '公众号'
                WHEN 2 THEN '小程序'
                WHEN 3 THEN 'H5'
                WHEN 4 THEN 'PC'
                WHEN 5 THEN 'APP'
                ELSE '其他'
            END AS source,
            COUNT(*) AS order_count,
            COALESCE(SUM(o.total_amount), 0) AS total_amount
        FROM public.ml_orders o
        WHERE o.created_at >= p_start_time
          AND o.created_at <= p_end_time
          AND o.order_status != 5
        GROUP BY o.channel_type
        ORDER BY order_count DESC
    ) t;

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