-- INTERLINK WhatsApp v2.6 - Rollback operativo seguro
-- No elimina datos, tickets, incidentes, conocimiento ni columnas.
-- Tolera una migración incompleta: solo actualiza cuando existen tabla y columnas.
USE `interlink_crm`;

SET @wa2_has_settings_table := (
  SELECT COUNT(*)
  FROM information_schema.tables
  WHERE table_schema=DATABASE() AND table_name='wa2_settings'
);
SET @wa2_has_rollback_columns := (
  SELECT COUNT(*)
  FROM information_schema.columns
  WHERE table_schema=DATABASE()
    AND table_name='wa2_settings'
    AND column_name IN (
      'ticket_auto_create_enabled',
      'incident_auto_reply_enabled',
      'operational_ai_refine_enabled'
    )
);
SET @wa2_sql := IF(
  @wa2_has_settings_table=1 AND @wa2_has_rollback_columns=3,
  'UPDATE wa2_settings SET ticket_auto_create_enabled=0, incident_auto_reply_enabled=0, operational_ai_refine_enabled=0, updated_at=NOW() WHERE id=1',
  "SELECT 'Advertencia: wa2_settings o las columnas v2.6 no existen; no fue necesario desactivar esos ajustes.' AS resultado"
);
PREPARE wa2_stmt FROM @wa2_sql;
EXECUTE wa2_stmt;
DEALLOCATE PREPARE wa2_stmt;

SET @wa2_has_incidents_table := (
  SELECT COUNT(*)
  FROM information_schema.tables
  WHERE table_schema=DATABASE() AND table_name='wa2_network_incidents'
);
SET @wa2_sql := IF(
  @wa2_has_incidents_table=1,
  'UPDATE wa2_network_incidents SET active=0, updated_at=NOW() WHERE active=1',
  "SELECT 'Advertencia: wa2_network_incidents no existe; no había incidencias v2.6 para desactivar.' AS resultado"
);
PREPARE wa2_stmt FROM @wa2_sql;
EXECUTE wa2_stmt;
DEALLOCATE PREPARE wa2_stmt;

SELECT 'Rollback seguro finalizado: automatismos disponibles fueron desactivados y todos los datos quedaron conservados.' AS resultado;
