-- ============================================================
-- Migration 023: Ingestion incidenti SIEM/SOC/EDR (P1 gap competitivo)
-- Aggiunge tracciamento sorgente + riferimento esterno (dedup) su incidents
-- Idempotente: usa procedura per ADD COLUMN IF NOT EXISTS
-- ============================================================

DELIMITER $$
DROP PROCEDURE IF EXISTS add_col_023 $$
CREATE PROCEDURE add_col_023()
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='incidents' AND COLUMN_NAME='source') THEN
        ALTER TABLE incidents ADD COLUMN source ENUM('manual','siem','soc','edr','api','email') NOT NULL DEFAULT 'manual' COMMENT 'Origine incidente (ingestion automatica vs manuale)' AFTER classification;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='incidents' AND COLUMN_NAME='source_system') THEN
        ALTER TABLE incidents ADD COLUMN source_system VARCHAR(120) NULL COMMENT 'Nome sistema sorgente (es. Splunk, Sentinel, CrowdStrike)' AFTER source;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='incidents' AND COLUMN_NAME='external_ref') THEN
        ALTER TABLE incidents ADD COLUMN external_ref VARCHAR(190) NULL COMMENT 'ID alert esterno (dedup ingestion)' AFTER source_system;
    END IF;
    -- Indice univoco per dedup ingestion (org + ref esterno). NULL ammessi multipli (incidenti manuali).
    IF NOT EXISTS (SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='incidents' AND INDEX_NAME='uq_incident_external_ref') THEN
        ALTER TABLE incidents ADD UNIQUE KEY uq_incident_external_ref (organization_id, external_ref);
    END IF;
END $$
DELIMITER ;
CALL add_col_023();
DROP PROCEDURE IF EXISTS add_col_023;
