CREATE TABLE reconcile_runs_v2 (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    host_id INTEGER NOT NULL,
    provider_id INTEGER NOT NULL,
    status TEXT NOT NULL,
    summary_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_reconcile_runs_host FOREIGN KEY (host_id) REFERENCES hosts(id) ON DELETE CASCADE,
    CONSTRAINT fk_reconcile_runs_provider FOREIGN KEY (provider_id) REFERENCES providers(id) ON DELETE CASCADE
);

INSERT INTO reconcile_runs_v2 (id, host_id, provider_id, status, summary_json, created_at)
SELECT rr.id, ib.host_id, rr.provider_id, rr.status, rr.summary_json, rr.created_at
FROM reconcile_runs rr
JOIN (
    SELECT provider_id, MAX(id) AS latest_batch_id
    FROM import_batches
    GROUP BY provider_id
) latest ON latest.provider_id = rr.provider_id
JOIN import_batches ib ON ib.id = latest.latest_batch_id;

DROP TABLE reconcile_runs;
ALTER TABLE reconcile_runs_v2 RENAME TO reconcile_runs;
