-- AZ-484: introduce per-source tile rows.
-- Adds `source` and `captured_at` columns, backfills existing rows to
-- (source='google_maps', captured_at=created_at), drops the 4-column unique index
-- created by migration 012 (idx_tiles_unique_location), and replaces it with a
-- 5-column unique index that includes `source`. The whole migration runs inside a
-- single transaction so a failure mid-flight cannot leave the table without its
-- unique index or with partially backfilled rows (per coderule.mdc and AZ-484
-- Risk 1 mitigation).

BEGIN;

ALTER TABLE tiles ADD COLUMN IF NOT EXISTS source VARCHAR(32);
ALTER TABLE tiles ADD COLUMN IF NOT EXISTS captured_at TIMESTAMP;

UPDATE tiles
SET source = 'google_maps'
WHERE source IS NULL;

UPDATE tiles
SET captured_at = created_at
WHERE captured_at IS NULL;

ALTER TABLE tiles ALTER COLUMN source SET NOT NULL;
ALTER TABLE tiles ALTER COLUMN captured_at SET NOT NULL;

DROP INDEX IF EXISTS idx_tiles_unique_location;

CREATE UNIQUE INDEX IF NOT EXISTS idx_tiles_unique_location_source
    ON tiles (latitude, longitude, tile_zoom, tile_size_meters, source);

COMMIT;
