-- =====================================================================================
-- Admin 商品统计 - 营业趋势统计 RPC
-- 位置：docs/sql/30_rpc/product/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：按天聚合指定时间范围内的商品浏览量、访客量、支付金额及退款金额
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_product_trend(
    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_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
            to_char(date_trunc('day', gs.day), 'YYYY-MM-DD') AS date_group,
            (SELECT COUNT(*) FROM public.ml_browse_history bh WHERE date_trunc('day', bh.created_at) = gs.day) as views,
            (SELECT COUNT(DISTINCT user_id) FROM public.ml_browse_history bh WHERE date_trunc('day', bh.created_at) = gs.day) as visitors,
            (SELECT COALESCE(SUM(total_amount), 0) FROM public.ml_orders o WHERE date_trunc('day', o.created_at) = gs.day AND o.order_status NOT IN (1, 5)) as pay_amount,
            (SELECT COALESCE(SUM(total_amount), 0) FROM public.ml_orders o WHERE date_trunc('day', o.created_at) = gs.day AND o.order_status = 7) as refund_amount
        FROM generate_series(date_trunc('day', p_start_time), date_trunc('day', p_end_time), '1 day'::interval) gs(day)
        ORDER BY gs.day ASC
    ) t;

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