-- =============================================================================
-- Migration 045: PChome auto-policy evidence receipts
-- MOMO PRO / PChome revenue growth automation
-- 2026-06-28 Taipei
-- =============================================================================
-- Notes:
--   Additive only. This migration creates a receipt ledger for controlled
--   PChome evidence persistence. It does not drop, truncate, rewrite, or
--   backfill external_offers / competitor_* / product sales tables.
-- =============================================================================

CREATE TABLE IF NOT EXISTS external_offer_evidence_receipts (
    receipt_id TEXT PRIMARY KEY,
    pchome_product_id TEXT NOT NULL,
    automation_decision TEXT NOT NULL,
    payload_hash TEXT NOT NULL,
    evidence_delta_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    applied_at TIMESTAMPTZ,
    apply_status TEXT NOT NULL DEFAULT 'previewed'
);
CREATE INDEX IF NOT EXISTS idx_external_offer_evidence_receipts_pchome_product_id ON external_offer_evidence_receipts (pchome_product_id);
CREATE INDEX IF NOT EXISTS idx_external_offer_evidence_receipts_payload_hash ON external_offer_evidence_receipts (payload_hash);
CREATE INDEX IF NOT EXISTS idx_external_offer_evidence_receipts_apply_status ON external_offer_evidence_receipts (apply_status);

GRANT ALL PRIVILEGES ON external_offer_evidence_receipts TO momo;

DO $$
BEGIN
    RAISE NOTICE 'Migration 045 complete: PChome auto-policy evidence receipts are ready';
END $$;
