-- =====================================================================================
-- Admin 订单统计 - 核心 KPI 汇总 RPC
-- 位置：docs/sql/30_rpc/order/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：获取指定时间段内的订单量、销售额、退款数及退款金额
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_order_stats(
    p_start_time TIMESTAMPTZ,
    p_end_time TIMESTAMPTZ
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_order_count BIGINT;
    v_total_amount DECIMAL(12,2);
    v_refund_count BIGINT;
    v_refund_amount DECIMAL(12,2);
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 
        COUNT(*), 
        COALESCE(SUM(total_amount), 0)
    INTO v_order_count, v_total_amount
    FROM public.ml_orders
    WHERE created_at >= p_start_time 
      AND created_at <= p_end_time
      AND order_status != 5; -- 5: 已取消

    -- 3. 统计退款汇总
    -- 注意：这里基于 ml_orders 的 payment_status 或 order_status 判断已退款
    SELECT 
        COUNT(*), 
        COALESCE(SUM(discount_amount), 0) -- 暂时用这个，若有真实退款金额字段请替换
    INTO v_refund_count, v_refund_amount
    FROM public.ml_orders
    WHERE created_at >= p_start_time 
      AND created_at <= p_end_time
      AND order_status IN (6, 7); -- 6: 退款中, 7: 已退款

    RETURN jsonb_build_object(
        'order_count', v_order_count,
        'total_amount', v_total_amount,
        'refund_count', v_refund_count,
        'refund_amount', v_refund_amount
    );
END;
$$;
