-- ============================================================
-- 门店月度目标表 ETL
-- 基于历史实际收入自动生成基准目标
-- 策略：用最近完整月份的实际收入作为下月目标基准，按区域增长率微调
-- ============================================================

-- 1. 创建目标表（如果不存在）
CREATE TABLE IF NOT EXISTS analytics.dim_store_target (
  id SERIAL PRIMARY KEY,
  store_code VARCHAR(20) NOT NULL,
  target_month DATE NOT NULL,
  revenue_target NUMERIC(12,2) NOT NULL,
  bill_count_target INTEGER,
  avg_bill_value_target NUMERIC(8,2),
  member_penetration_target NUMERIC(5,2), -- 百分比
  cost_rate_target NUMERIC(5,2), -- 百分比
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW(),
  UNIQUE(store_code, target_month)
);

-- 2. 生成2026-05目标（基于4月实际 × 增长系数1.03）
INSERT INTO analytics.dim_store_target (store_code, target_month, revenue_target, bill_count_target, avg_bill_value_target, member_penetration_target, cost_rate_target)
SELECT 
  r.store_code,
  '2026-05-01'::date,
  round(r.received * 1.03, 2) as revenue_target,
  round(r.bill_count * 1.03) as bill_count_target,
  round(r.avg_bill_value, 2) as avg_bill_value_target,
  round(r.member_bill_share_pct, 2) as member_penetration_target,
  30.00 as cost_rate_target
FROM analytics.mv_store_risk_rating_monthly r
WHERE r.month_start = '2026-04-01'
ON CONFLICT (store_code, target_month) DO UPDATE SET
  revenue_target = EXCLUDED.revenue_target,
  bill_count_target = EXCLUDED.bill_count_target,
  avg_bill_value_target = EXCLUDED.avg_bill_value_target,
  member_penetration_target = EXCLUDED.member_penetration_target,
  cost_rate_target = EXCLUDED.cost_rate_target,
  updated_at = NOW();

-- 3. 生成2026-04目标（用4月实际作为回顾目标，方便展示达成率）
INSERT INTO analytics.dim_store_target (store_code, target_month, revenue_target, bill_count_target, avg_bill_value_target, member_penetration_target, cost_rate_target)
SELECT 
  r.store_code,
  '2026-04-01'::date,
  round(r.received, 2) as revenue_target,
  r.bill_count as bill_count_target,
  round(r.avg_bill_value, 2) as avg_bill_value_target,
  round(r.member_bill_share_pct, 2) as member_penetration_target,
  30.00 as cost_rate_target
FROM analytics.mv_store_risk_rating_monthly r
WHERE r.month_start = '2026-04-01'
ON CONFLICT (store_code, target_month) DO UPDATE SET
  revenue_target = EXCLUDED.revenue_target,
  bill_count_target = EXCLUDED.bill_count_target,
  avg_bill_value_target = EXCLUDED.avg_bill_value_target,
  member_penetration_target = EXCLUDED.member_penetration_target,
  cost_rate_target = EXCLUDED.cost_rate_target,
  updated_at = NOW();

-- 4. 验证
SELECT '2026-04' as month, count(*) as stores, round(sum(revenue_target)::numeric, 2) as total_target 
FROM analytics.dim_store_target WHERE target_month = '2026-04-01'
UNION ALL
SELECT '2026-05', count(*), round(sum(revenue_target)::numeric, 2)
FROM analytics.dim_store_target WHERE target_month = '2026-05-01';
