-- One-shot inversion of bulk_address_uploads.column_mapping.
--
-- Old shape: { "<source header>": "<internal field>" } (header -> field), with
-- unmapped columns stored as "<header>": "skip".
-- New shape: { "<internal field>": "<source header>" } (field -> header), with
-- unmapped fields simply absent. See ADR-0003 and the WIP plan (Q2.2/Q5).
--
-- 'skip' entries are dropped. On a legacy duplicate (two headers -> one field),
-- jsonb_object_agg keeps the last header — the new address-uniqueness rule
-- forbids that going forward anyway. No-op on NULL/empty mappings, so this is
-- safe regardless of data volume. One-shot: assumes rows are still old-shape.
UPDATE "bulk_address_uploads"
SET "column_mapping" = COALESCE(
  (
    SELECT jsonb_object_agg(elem.value, elem.key)
    FROM jsonb_each_text("column_mapping") AS elem
    WHERE elem.value <> 'skip'
  ),
  '{}'::jsonb
)
WHERE "column_mapping" IS NOT NULL
  AND "column_mapping" <> '{}'::jsonb;
