-- Sprint 24A FIX2 — endurecimiento comercial
-- Idempotente y reversible mediante snapshot del instalador.

-- Los planes personales no usan trial profesional.
UPDATE billing_suscripciones s
JOIN billing_planes p ON p.id=s.id_plan
SET s.estado='activa',
    s.trial_fin=NULL,
    s.periodo_fin=GREATEST(COALESCE(s.periodo_fin,NOW()),DATE_ADD(NOW(),INTERVAL 10 YEAR)),
    s.actualizado_en=NOW()
WHERE p.codigo IN ('starter','family') AND s.estado='trial';

UPDATE org_empresas e
JOIN billing_suscripciones s ON s.id_empresa=e.id
JOIN billing_planes p ON p.id=s.id_plan
SET e.estado='activo',e.actualizado_en=NOW()
WHERE p.codigo IN ('starter','family') AND e.estado='trial';

-- Los trials profesionales quedan limitados a 14 días.
UPDATE billing_suscripciones s
JOIN billing_planes p ON p.id=s.id_plan
SET s.trial_fin=DATE_ADD(s.periodo_inicio,INTERVAL 14 DAY),
    s.periodo_fin=DATE_ADD(s.periodo_inicio,INTERVAL 14 DAY),
    s.actualizado_en=NOW()
WHERE p.codigo IN ('pro','studio') AND s.estado='trial';

-- Índices para procesar vencimientos y cambios programados.
SET @idx_trial = (
 SELECT COUNT(*) FROM information_schema.statistics
 WHERE table_schema=DATABASE() AND table_name='billing_suscripciones'
   AND index_name='idx_billing_trial_expiry'
);
SET @sql_trial = IF(@idx_trial=0,
 'ALTER TABLE billing_suscripciones ADD INDEX idx_billing_trial_expiry (estado,trial_fin)',
 'SELECT 1');
PREPARE stmt_trial FROM @sql_trial; EXECUTE stmt_trial; DEALLOCATE PREPARE stmt_trial;

SET @idx_change = (
 SELECT COUNT(*) FROM information_schema.statistics
 WHERE table_schema=DATABASE() AND table_name='billing_suscripciones'
   AND index_name='idx_billing_scheduled_change'
);
SET @sql_change = IF(@idx_change=0,
 'ALTER TABLE billing_suscripciones ADD INDEX idx_billing_scheduled_change (proximo_plan_id,cambio_programado_en)',
 'SELECT 1');
PREPARE stmt_change FROM @sql_change; EXECUTE stmt_change; DEALLOCATE PREPARE stmt_change;
