-- AZ-357 / C06: drop year-based versioning from the tile uniqueness key.
-- The 'version' column itself is preserved (intentionally; column drops require
-- explicit confirmation per coderule.mdc). This migration:
--   1. Drops the 5-column unique index that includes version.
--   2. Dedupes pre-existing duplicates by the new 4-column key, keeping the row
--      with the highest updated_at (tie-break: highest id).
--   3. Recreates the unique index without version.
--   4. Makes the version column nullable and drops its default so new rows can
--      be inserted without writing a meaningless year value.

DROP INDEX IF EXISTS idx_tiles_unique_location;

DELETE FROM tiles
WHERE id IN (
    SELECT id
    FROM (
        SELECT id,
               ROW_NUMBER() OVER (
                   PARTITION BY latitude, longitude, tile_zoom, tile_size_meters
                   ORDER BY updated_at DESC, id DESC
               ) AS rn
        FROM tiles
    ) ranked
    WHERE rn > 1
);

CREATE UNIQUE INDEX idx_tiles_unique_location
    ON tiles(latitude, longitude, tile_zoom, tile_size_meters);

ALTER TABLE tiles ALTER COLUMN version DROP NOT NULL;
ALTER TABLE tiles ALTER COLUMN version DROP DEFAULT;
