-- Reconcile the system_settings unique-index drift surfaced in the
-- final-deferred audit. The Drizzle schema declares a uniqueIndex on
-- (key, port_id), but Postgres treats NULL values as distinct by default.
-- That means two rows with `(same_key, NULL)` would BOTH be allowed -
-- a global-setting collision the index claims to prevent.
--
-- This was not just theoretical: the dev DB had 60+ duplicate
-- `(storage_backend, NULL)` rows from buggy non-upsert call sites that
-- predated the upsert hardening. Those rows accumulated invisibly because
-- the index allowed them. Step 1 dedupes (keeps the most recent row per
-- `(key, port_id)` group); step 2 rebuilds the unique index with
-- `NULLS NOT DISTINCT` (Postgres 15+) so future inserts can't recreate the
-- ambiguity.

-- Step 1: dedupe duplicate rows, keeping the row with the latest updated_at.
-- Uses a CTE + ROW_NUMBER() so the keeper is deterministic across reruns.
WITH ranked AS (
  SELECT ctid,
         ROW_NUMBER() OVER (
           PARTITION BY "key", "port_id"
           ORDER BY "updated_at" DESC, ctid DESC
         ) AS rn
  FROM "system_settings"
)
DELETE FROM "system_settings"
USING ranked
WHERE "system_settings".ctid = ranked.ctid AND ranked.rn > 1;

-- Step 2: replace the unique index with one that treats NULLs as equal,
-- so global settings (port_id IS NULL) are unique by key alone.
DROP INDEX IF EXISTS "system_settings_key_port_idx";
CREATE UNIQUE INDEX "system_settings_key_port_idx"
  ON "system_settings" ("key", "port_id")
  NULLS NOT DISTINCT;
