-- ============================================================================
-- Migration 021 - Tassonomia Incidenti NIS2 (Determina ACN 164179/2025)
-- ----------------------------------------------------------------------------
-- Aggiunge alla tabella incidents:
--  - nis2_incident_type: tipologia incidente significativo IS-1/IS-2/IS-3/IS-4
--    (Determinazione ACN n. 164179 del 14/04/2025, Allegati 3 e 4).
--  - entity_obligation: regime di obblighi applicabile (essential=Allegato 3,
--    important=Allegato 4). I soggetti importanti NON sono tenuti all'IS-4
--    (incidenti ricorrenti).
--
-- Fonte: D.Lgs. 138/2024 art. 23 + Determina ACN 164179/2025.
-- Idempotente via information_schema. Rilanciabile.
--   mysql -h localhost nis2_agile_db -e "source docs/sql/021_incident_nis2_taxonomy.sql"
-- ============================================================================

DELIMITER //
DROP PROCEDURE IF EXISTS _mig021_add_col //
CREATE PROCEDURE _mig021_add_col(IN col VARCHAR(64), IN ddl TEXT)
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'incidents' AND COLUMN_NAME = col
    ) THEN
        SET @sql = CONCAT('ALTER TABLE incidents ADD COLUMN ', ddl);
        PREPARE st FROM @sql; EXECUTE st; DEALLOCATE PREPARE st;
    END IF;
END //
DELIMITER ;

CALL _mig021_add_col('nis2_incident_type', "nis2_incident_type ENUM('IS-1','IS-2','IS-3','IS-4') NULL COMMENT 'Tipologia incidente significativo - Determina ACN 164179/2025'");
CALL _mig021_add_col('entity_obligation',  "entity_obligation ENUM('essential','important') NULL COMMENT 'Regime obblighi: essential=Allegato 3, important=Allegato 4'");

DROP PROCEDURE IF EXISTS _mig021_add_col;

-- ROLLBACK:
-- ALTER TABLE incidents DROP COLUMN nis2_incident_type, DROP COLUMN entity_obligation;
