-- 2026_07_21_001_exhibition_revenue_idempotent.sql
-- 批次1.1+1.3：展品收益结算幂等 + created_at 单位统一
-- 执行前请先备份：
--   pg_dump -h <host> -U postgres -t exhibition_revenue_records -t exhibitions <db> > backup_1_1.sql

BEGIN;

-- (1.3) created_at 秒→毫秒回填（10 位秒 → 13 位毫秒）
UPDATE exhibition_revenue_records
SET created_at = created_at * 1000
WHERE created_at > 0 AND created_at < 100000000000;

-- (1.1) 历史去重：同一 (exhibition_id, cycle_start_time) 只保留 id 最小的一条
DELETE FROM exhibition_revenue_records a
USING exhibition_revenue_records b
WHERE a.exhibition_id = b.exhibition_id
  AND a.cycle_start_time = b.cycle_start_time
  AND a.id > b.id;

-- (1.1) 唯一约束（幂等基石）
ALTER TABLE exhibition_revenue_records
  ADD CONSTRAINT uk_exhibition_revenue_cycle UNIQUE (exhibition_id, cycle_start_time);

-- (settled_at) 独立审计列，替代复用 is_processed
ALTER TABLE exhibitions ADD COLUMN IF NOT EXISTS settled_at bigint;
-- 回填：已被当作 settled 的历史行（is_processed=true）迁移到 settled_at
UPDATE exhibitions SET settled_at = COALESCE(updated_at, EXTRACT(EPOCH FROM now())*1000)
WHERE is_processed = true AND settled_at IS NULL;

-- 序列同步（CLAUDE.md 强制）
SELECT setval('exhibition_revenue_records_id_seq', (SELECT COALESCE(MAX(id),1) FROM exhibition_revenue_records));

COMMIT;