-- =====================================================================================
-- 数据分析模块（正式RPC，主库 ml_* 口径）
-- 文件: 04_ml_analytics_rpcs_market_trends.sql
-- 主题: 市场趋势（整体趋势/类目对比/季节性/价格趋势/竞争格局）
--
-- 说明：该模块历史上依赖测试库中的 RPC（rpc_analytics_market_trend_daily 等）。
-- 这里基于主库 ml_* 表重建：
-- - 订单：ml_orders / ml_order_items
-- - 商品/类目：ml_products / ml_categories
-- - 用户活跃（弱口径）：ml_browse_history
--
-- 口径约定：
-- - GMV：支付订单的 paid_amount（为 0 时用 total_amount 兜底）
-- - orders：订单数（支付订单口径：payment_status=2）
-- - users：活跃用户（浏览口径：ml_browse_history 去重 user_id）
-- - avg_price：支付订单下的件单价（sum(订单明细金额)/sum(件数)）
-- =====================================================================================

-- 1) 市场整体趋势（日维度）
-- 返回字段需要匹配页面 buildChartOptions 使用的：day/gmv/orders/users
CREATE OR REPLACE FUNCTION public.rpc_analytics_market_trend_daily(
  p_start TIMESTAMPTZ,
  p_end TIMESTAMPTZ
)
RETURNS TABLE (
  day TEXT,
  gmv NUMERIC,
  orders BIGINT,
  users BIGINT
)
LANGUAGE sql
AS $$
  WITH date_series AS (
    SELECT generate_series(date_trunc('day', p_start), date_trunc('day', p_end), interval '1 day')::date AS d
  ),
  paid_orders AS (
    SELECT
      o.id,
      o.user_id,
      o.created_at::date AS d,
      COALESCE(NULLIF(o.paid_amount, 0), o.total_amount) AS paid_gmv
    FROM public.ml_orders o
    WHERE o.payment_status = 2
      AND o.created_at >= p_start
      AND o.created_at < (p_end + interval '1 second')
  ),
  active_users AS (
    SELECT
      bh.created_at::date AS d,
      COUNT(DISTINCT bh.user_id)::bigint AS users
    FROM public.ml_browse_history bh
    WHERE bh.created_at >= p_start
      AND bh.created_at < (p_end + interval '1 second')
    GROUP BY bh.created_at::date
  )
  SELECT
    to_char(ds.d, 'YYYY-MM-DD') AS day,
    COALESCE(SUM(po.paid_gmv), 0) AS gmv,
    COUNT(po.id)::bigint AS orders,
    COALESCE(au.users, 0) AS users
  FROM date_series ds
  LEFT JOIN paid_orders po ON po.d = ds.d
  LEFT JOIN active_users au ON au.d = ds.d
  GROUP BY ds.d, au.users
  ORDER BY ds.d;
$$;


-- 2) 类目销售（类目 GMV 排行）
-- 返回字段匹配页面：category_name / total_sales
CREATE OR REPLACE FUNCTION public.rpc_analytics_category_sales(
  p_start_date DATE,
  p_end_date DATE
)
RETURNS TABLE (
  category_name TEXT,
  total_sales NUMERIC
)
LANGUAGE sql
AS $$
  SELECT
    COALESCE(c.name, '未分类')::text AS category_name,
    COALESCE(SUM(oi.total_amount), 0) AS total_sales
  FROM public.ml_order_items oi
  JOIN public.ml_orders o ON o.id = oi.order_id
  LEFT JOIN public.ml_products p ON p.id = oi.product_id
  LEFT JOIN public.ml_categories c ON c.id = p.category_id
  WHERE o.payment_status = 2
    AND o.created_at::date BETWEEN p_start_date AND p_end_date
  GROUP BY c.name
  ORDER BY total_sales DESC;
$$;


-- 3) 季节性趋势（按月 GMV）
-- 返回字段匹配页面：month / total_gmv
CREATE OR REPLACE FUNCTION public.rpc_analytics_seasonal_trend(
  p_start_date DATE,
  p_end_date DATE
)
RETURNS TABLE (
  month TEXT,
  total_gmv NUMERIC
)
LANGUAGE sql
AS $$
  SELECT
    to_char(date_trunc('month', o.created_at), 'YYYY-MM') AS month,
    COALESCE(SUM(COALESCE(NULLIF(o.paid_amount, 0), o.total_amount)), 0) AS total_gmv
  FROM public.ml_orders o
  WHERE o.payment_status = 2
    AND o.created_at::date BETWEEN p_start_date AND p_end_date
  GROUP BY date_trunc('month', o.created_at)
  ORDER BY date_trunc('month', o.created_at);
$$;


-- 4) 价格趋势（按天件单价）
-- 返回字段匹配页面：day / avg_price
CREATE OR REPLACE FUNCTION public.rpc_analytics_price_trend(
  p_start TIMESTAMPTZ,
  p_end TIMESTAMPTZ
)
RETURNS TABLE (
  day TEXT,
  avg_price NUMERIC
)
LANGUAGE sql
AS $$
  WITH date_series AS (
    SELECT generate_series(date_trunc('day', p_start), date_trunc('day', p_end), interval '1 day')::date AS d
  ),
  paid_items AS (
    SELECT
      o.created_at::date AS d,
      SUM(oi.total_amount) AS amt,
      SUM(oi.quantity) AS qty
    FROM public.ml_orders o
    JOIN public.ml_order_items oi ON oi.order_id = o.id
    WHERE o.payment_status = 2
      AND o.created_at >= p_start
      AND o.created_at < (p_end + interval '1 second')
    GROUP BY o.created_at::date
  )
  SELECT
    to_char(ds.d, 'YYYY-MM-DD') AS day,
    CASE WHEN COALESCE(pi.qty, 0) > 0 THEN ROUND((pi.amt / pi.qty)::numeric, 2) ELSE 0 END AS avg_price
  FROM date_series ds
  LEFT JOIN paid_items pi ON pi.d = ds.d
  ORDER BY ds.d;
$$;


-- 5) 竞争分析（商家 GMV 份额）
-- 返回字段匹配页面：merchant_name / gmv
CREATE OR REPLACE FUNCTION public.rpc_analytics_competition_share(
  p_start_date DATE,
  p_end_date DATE
)
RETURNS TABLE (
  merchant_name TEXT,
  gmv NUMERIC
)
LANGUAGE sql
AS $$
  SELECT
    COALESCE(NULLIF(m.username, ''), '未知商家')::text AS merchant_name,
    COALESCE(SUM(COALESCE(NULLIF(o.paid_amount, 0), o.total_amount)), 0) AS gmv
  FROM public.ml_orders o
  JOIN public.ak_users m ON m.id = o.merchant_id
  WHERE o.payment_status = 2
    AND o.created_at::date BETWEEN p_start_date AND p_end_date
  GROUP BY m.username
  ORDER BY gmv DESC;
$$;
