-- =====================================================================================
-- 数据分析模块（正式RPC，主库 ml_* 口径）
-- 文件: 08_ml_analytics_rpcs_data_detail.sql
-- 主题: 数据详情页 (下钻/对比)
-- =====================================================================================

-- 1) 数据下钻
CREATE OR REPLACE FUNCTION public.rpc_data_detail_drill_items(
  p_report_id TEXT,
  p_filters JSONB
)
RETURNS TABLE (
  item_id TEXT,
  item_name TEXT,
  gmv NUMERIC,
  orders BIGINT
)
LANGUAGE sql
AS $$
  -- 模拟返回，实际应根据 p_report_id 和 p_filters 查询
  SELECT
    'prod-001' AS item_id,
    '商品A' AS item_name,
    12000 AS gmv,
    300 AS orders
  UNION ALL
  SELECT
    'prod-002' AS item_id,
    '商品B' AS item_name,
    8000 AS gmv,
    200 AS orders;
$$;


-- 2) GMV 对比
CREATE OR REPLACE FUNCTION public.rpc_data_detail_compare_gmv(
  p_item_id TEXT,
  p_period TEXT
)
RETURNS TABLE (
  date TEXT,
  current_gmv NUMERIC,
  previous_gmv NUMERIC
)
LANGUAGE sql
AS $$
  -- 模拟返回
  SELECT
    d.date,
    (1000 + random() * 500) AS current_gmv,
    (800 + random() * 400) AS previous_gmv
  FROM generate_series(CURRENT_DATE - interval '6 days', CURRENT_DATE, '1 day') AS d(date);
$$;
