-- ============================================================================
-- Migration 025 - Asset import CMDB/cloud (P2)
-- ----------------------------------------------------------------------------
-- Abilita l'import bulk asset da CMDB/export cloud con dedup idempotente:
--   - assets.external_ref     : ID asset nel sistema sorgente (CMDB/cloud)
--   - assets.discovery_source : provenienza (cmdb/aws/azure/csv/manual/...)
-- + indice univoco (organization_id, external_ref) per upsert.
--
-- Idempotente via information_schema. Rilanciabile.
--   mysql -h localhost nis2_agile_db -e "source docs/sql/025_asset_import.sql"
-- ============================================================================

DELIMITER //
DROP PROCEDURE IF EXISTS _mig025 //
CREATE PROCEDURE _mig025()
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='assets' AND COLUMN_NAME='external_ref') THEN
        ALTER TABLE assets ADD COLUMN external_ref VARCHAR(190) NULL COMMENT 'ID asset nel sistema sorgente (dedup import)' AFTER serial_number;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='assets' AND COLUMN_NAME='discovery_source') THEN
        ALTER TABLE assets ADD COLUMN discovery_source VARCHAR(40) NOT NULL DEFAULT 'manual' COMMENT 'Provenienza asset (cmdb/aws/azure/csv/manual)' AFTER external_ref;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='assets' AND INDEX_NAME='uq_asset_external_ref') THEN
        ALTER TABLE assets ADD UNIQUE KEY uq_asset_external_ref (organization_id, external_ref);
    END IF;
END //
DELIMITER ;
CALL _mig025();
DROP PROCEDURE IF EXISTS _mig025;

-- ROLLBACK:
-- ALTER TABLE assets DROP INDEX uq_asset_external_ref, DROP COLUMN external_ref, DROP COLUMN discovery_source;
