-- =====================================================================================
-- Admin 订单统计 - 趋势统计 RPC
-- 位置：docs/sql/30_rpc/order/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：按天聚合指定时间范围内的订单量/销售额/退款量/退款金额
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_order_trend(
    p_start_time TIMESTAMPTZ,
    p_end_time TIMESTAMPTZ,
    p_group_by TEXT DEFAULT 'day'
)
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. 目前仅支持 day
    IF p_group_by IS NULL OR p_group_by != 'day' THEN
        RAISE EXCEPTION 'Unsupported group_by';
    END IF;

    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT
            to_char(date_trunc('day', o.created_at), 'YYYY-MM-DD') AS date_group,
            COUNT(*) FILTER (WHERE o.order_status != 5) AS order_count,
            COALESCE(SUM(o.total_amount) FILTER (WHERE o.order_status != 5), 0) AS total_amount,
            COUNT(*) FILTER (WHERE o.order_status IN (6, 7)) AS refund_count,
            COALESCE(SUM(o.discount_amount) FILTER (WHERE o.order_status IN (6, 7)), 0) AS refund_amount
        FROM public.ml_orders o
        WHERE o.created_at >= p_start_time
          AND o.created_at <= p_end_time
        GROUP BY date_trunc('day', o.created_at)
        ORDER BY date_trunc('day', o.created_at) ASC
    ) t;

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