-- FinOps only. Stop Azure Bronze/Usage/FOCUS/Gold and tag discovery first.
-- Additive: no source or financial row is deleted by this migration.
CREATE TABLE IF NOT EXISTS azure_sponsorship_pipeline_state (
    id INT NOT NULL,
    revision BIGINT UNSIGNED NOT NULL DEFAULT 0,
    PRIMARY KEY (id)
) ENGINE=InnoDB;
INSERT IGNORE INTO azure_sponsorship_pipeline_state (id, revision) VALUES (1, 0);

CREATE TABLE IF NOT EXISTS azure_sponsorship_snapshot (
    revision BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    stage VARCHAR(20) NOT NULL,
    business_date DATE NOT NULL,
    scope_id VARCHAR(128) NOT NULL,
    ingestion_run_id CHAR(36) NOT NULL,
    row_count BIGINT UNSIGNED NOT NULL,
    published_at DATETIME(6) NOT NULL,
    PRIMARY KEY (revision),
    UNIQUE KEY uk_azure_snapshot_run (stage, business_date, scope_id, ingestion_run_id),
    KEY idx_azure_snapshot_day (stage, business_date, scope_id, revision)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

CREATE TABLE IF NOT EXISTS azure_sponsorship_gold_refresh_day (
    business_date DATE NOT NULL,
    usage_date DATE NOT NULL,
    PRIMARY KEY (business_date, usage_date)
) ENGINE=InnoDB;

-- Old Bronze was inserted atomically after ALL API pages were fetched.
-- Import only identifiable nonempty runs, without merging hashes or runs.
-- Older empty responses have no durable evidence: reacquire their days.
START TRANSACTION;
INSERT IGNORE INTO azure_sponsorship_snapshot
    (stage, business_date, scope_id, ingestion_run_id, row_count, published_at)
SELECT 'BRONZE', b.business_date, b.scope_id, b.ingestion_run_id, COUNT(*), MAX(b.ingestion_time)
FROM azure_sponsorship_billing_bronze b
WHERE b.scope_id IS NOT NULL AND b.scope_id<>''
  AND b.ingestion_run_id IS NOT NULL AND b.ingestion_run_id<>''
GROUP BY b.business_date, b.scope_id, b.ingestion_run_id
ORDER BY MAX(b.ingestion_time), MAX(b.id);

UPDATE azure_sponsorship_pipeline_state
SET revision=GREATEST(revision, (SELECT COALESCE(MAX(revision),0) FROM azure_sponsorship_snapshot))
WHERE id=1;

-- Preserve usage dates of legacy FOCUS rows so removed lines can retract Gold.
INSERT IGNORE INTO azure_sponsorship_gold_refresh_day (business_date, usage_date)
SELECT DISTINCT business_date, DATE(ChargePeriodStart)
FROM azure_sponsorship_focus_silver WHERE ChargePeriodStart IS NOT NULL;
COMMIT;
