-- ============================================================
-- Toasty — Migration 006 : Index unique robuste sur subscribers.endpoint
-- MySQL 8.0.29+
-- Idempotent : ADD COLUMN IF NOT EXISTS + ADD UNIQUE INDEX IF NOT EXISTS
-- Remplace le partial-index unique_endpoint(255) par un hash SHA-256,
-- car TEXT ne peut pas être indexé directement sur sa longueur complète.
-- ============================================================

-- Colonne hash SHA-256 de l'endpoint (endpoint est TEXT, trop long pour un index direct)
ALTER TABLE subscribers
    ADD COLUMN IF NOT EXISTS endpoint_hash CHAR(64) NULL
    COMMENT 'SHA-256 hex de endpoint — utilisé pour le dédoublonnage'
    AFTER endpoint;

-- Backfill des lignes existantes
UPDATE subscribers
SET endpoint_hash = SHA2(endpoint, 256)
WHERE endpoint IS NOT NULL
  AND endpoint_hash IS NULL;

-- Index unique robuste (shop_id, endpoint_hash)
ALTER TABLE subscribers
    ADD UNIQUE INDEX IF NOT EXISTS idx_unique_endpoint_hash (shop_id, endpoint_hash);
