-- Coconut Trade Fair non-destructive schema upgrade.
--
-- Duplicate normalized email addresses are allowed in production. This
-- migration does not add a normalizedEmail unique key and never drops rows,
-- labels, or existing indexes. The ALTER TABLE statements preserve existing
-- column values while widening the label columns to TEXT.

-- IMPORTANT: this migration assumes the destination schema has the same
-- tables/columns as sql/schema.sql. For an older dump that lacks
-- registrants.normalizedEmail, the ADD COLUMN below is the compatibility step.

-- 1) Long-form registration labels (including Data Privacy consent text).
ALTER TABLE `registration_fields`
  MODIFY COLUMN `label` TEXT NOT NULL;

-- registration_field_answers stores a readable copy of the field label. Keep
-- that copy unbounded as well, otherwise submitting a form with a long label
-- could fail even after registration_fields.label is widened.
ALTER TABLE `registration_field_answers`
  MODIFY COLUMN `fieldLabel` TEXT NOT NULL;

-- 2) Add the nullable normalized lookup key.
ALTER TABLE `registrants`
  ADD COLUMN `normalizedEmail` VARCHAR(255) NULL AFTER `email`;

-- Populate only the new key. Existing email values are not rewritten, and no
-- address or label data is truncated.
UPDATE `registrants`
SET `normalizedEmail` = CASE
    WHEN `active` = 1 AND `email` IS NOT NULL THEN LOWER(TRIM(`email`))
    ELSE NULL
  END;

-- Duplicate active rows are intentional. Do not add
-- `uq_registrants_active_normalized_email`; normalizedEmail is for lookup and
-- resend resolution, not uniqueness.
