-- Migration 012: per-domain version tracking
-- Each domain gets its own version number.
-- It starts at the current global version and increments when:
--   1. Model/price data changes (all domains bump together via scraper)
--   2. The domain's discount changes (only that domain bumps)
SET search_path TO crawl;

CREATE TABLE IF NOT EXISTS domain_version (
    domain     VARCHAR(255) PRIMARY KEY,
    version    BIGINT       NOT NULL DEFAULT 1,
    updated_at TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

COMMENT ON TABLE domain_version IS
    'Per-domain version number. Increments on model data changes or discount changes for that domain.';

-- 回填已有折扣域名，初始版本为 1
INSERT INTO domain_version (domain, version, updated_at)
SELECT domain, 1, NOW()
FROM discounts
ON CONFLICT (domain) DO NOTHING;
