-- The policy type the OCR parser read the product as, resolved to a
-- `policy_types` row at confirm time.
ALTER TABLE `policy_ocr_documents`
    ADD COLUMN `extractedPolicyTypeName` VARCHAR(191) NULL;

-- ---------------------------------------------------------------------------
-- Repair: M_EMPR was deleted from the lookups screen and took its policies'
-- type with it.
--
-- `policies.policyTypeId` is ON DELETE SET NULL, and removePolicyType() had no
-- in-use guard, so deleting the row silently blanked the field on every policy
-- referencing it — 5 of them, all from the legacy `m_empr` table. The guard
-- against a repeat ships in the same change as this migration. What follows
-- repairs what already happened.
--
-- Idempotent on purpose: `policy_types.name` is UNIQUE so the INSERT IGNORE is
-- a no-op once the row exists, and the UPDATE is scoped to rows that are still
-- null AND came from that one legacy table, so it can never claim a policy
-- whose type was blanked for some other reason.
INSERT IGNORE INTO `policy_types` (`id`, `name`) VALUES (UUID(), 'M_EMPR');

UPDATE `policies` p
    JOIN `policy_types` pt ON pt.`name` = 'M_EMPR'
    SET p.`policyTypeId` = pt.`id`
    WHERE p.`policyTypeId` IS NULL
      AND p.`legacySourceTable` = 'm_empr';

-- INCENDIO is deliberately NOT recreated. It is the other row the migration
-- would have produced, but no policy in the book has ever carried it, so
-- adding it back would only put a dead option in the type picker.

-- ---------------------------------------------------------------------------
-- Merge the duplicate ANA carrier.
--
-- `insurance_providers` holds both "ANA" (1 policy) and "ANA SEGUROS" (738).
-- They are one carrier, and OCR is about to start assigning it automatically —
-- picking either row while both exist would keep splitting the book.
--
-- "ANA SEGUROS" is the survivor because it is where the 738 already are.
--
-- Written as joins rather than subqueries so that BOTH statements are no-ops
-- when either row is absent (a fresh database, or one where this was already
-- tidied by hand). A subquery form would resolve to NULL and blank the
-- carrier off every ANA policy.
UPDATE `policies` p
    JOIN `insurance_providers` dup  ON dup.`id` = p.`insuranceProviderId` AND dup.`name` = 'ANA'
    JOIN `insurance_providers` keep ON keep.`name` = 'ANA SEGUROS'
    SET p.`insuranceProviderId` = keep.`id`;

DELETE dup FROM `insurance_providers` dup
    JOIN `insurance_providers` keep ON keep.`name` = 'ANA SEGUROS'
    WHERE dup.`name` = 'ANA'
      -- Belt and braces: never drop a row that still has policies hanging off
      -- it, whatever the UPDATE above did or did not manage to move.
      AND NOT EXISTS (SELECT 1 FROM `policies` p WHERE p.`insuranceProviderId` = dup.`id`);
