UPDATE site_domain_mappings
SET registrable_domain = LOWER(TRIM(registrable_domain)),
    site_key = LOWER(TRIM(site_key)),
    site_name = TRIM(site_name);

DELETE FROM site_domain_mappings older
USING site_domain_mappings newer
WHERE older.registrable_domain = newer.registrable_domain
  AND older.id < newer.id;

DROP INDEX IF EXISTS idx_site_domain_mappings_lookup;

ALTER TABLE site_domain_mappings
    DROP COLUMN IF EXISTS tenant_id,
    ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();

CREATE UNIQUE INDEX IF NOT EXISTS uk_site_domain_mappings_domain
    ON site_domain_mappings(registrable_domain);

CREATE INDEX IF NOT EXISTS idx_site_domain_mappings_active_domain
    ON site_domain_mappings(registrable_domain) WHERE is_active = TRUE;

CREATE INDEX IF NOT EXISTS idx_site_domain_mappings_created
    ON site_domain_mappings(created_at DESC, id DESC);
