-- ============================================================================
-- Migration 033 - suppliers: categoria, provenienza import, soft-delete (guard)
-- ----------------------------------------------------------------------------
-- PROPOSTA DI DESIGN (NON ancora applicata). Da eseguire su host MySQL.
--
-- Estende suppliers per il nuovo modulo questionari/import:
--   - category_id  : FK supplier_categories (classificazione fornitore)
--   - external_ref : ID nel sistema sorgente (dedup import API/CSV)
--   - source       : ENUM('manual','csv','api') provenienza del record
--   - deleted_at   : soft-delete -- GIA PRESENTE da mig 006; aggiunto solo se assente
-- + UNIQUE(organization_id, external_ref) per upsert idempotente.
--
-- NOTA REALE: suppliers.deleted_at e stato aggiunto dalla migration 006.
-- Questo script lo riaggiunge SOLO se mancante. Nessuna duplicazione.
--
-- IMPORTANTE: MySQL 8 Ubuntu NON supporta "ADD COLUMN IF NOT EXISTS".
-- Procedura idempotente su information_schema. DELIMITER -> usare "source".
--   mysql -h localhost nis2_agile_db -e "source docs/sql/033_suppliers_category_source.sql"
-- ============================================================================

DELIMITER //
DROP PROCEDURE IF EXISTS _mig033 //
CREATE PROCEDURE _mig033()
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                   WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='suppliers' AND COLUMN_NAME='category_id') THEN
        ALTER TABLE suppliers ADD COLUMN category_id INT NULL
            COMMENT 'FK supplier_categories: classificazione fornitore' AFTER service_type;
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                   WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='suppliers' AND COLUMN_NAME='external_ref') THEN
        ALTER TABLE suppliers ADD COLUMN external_ref VARCHAR(190) NULL
            COMMENT 'ID fornitore nel sistema sorgente (dedup import API/CSV)' AFTER vat_number;
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                   WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='suppliers' AND COLUMN_NAME='source') THEN
        ALTER TABLE suppliers ADD COLUMN source ENUM('manual','csv','api') NOT NULL DEFAULT 'manual'
            COMMENT 'Provenienza del record fornitore' AFTER external_ref;
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                   WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='suppliers' AND COLUMN_NAME='deleted_at') THEN
        ALTER TABLE suppliers ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL AFTER updated_at;
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.TABLE_CONSTRAINTS
                   WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='suppliers'
                     AND CONSTRAINT_NAME='fk_supplier_category' AND CONSTRAINT_TYPE='FOREIGN KEY') THEN
        ALTER TABLE suppliers ADD CONSTRAINT fk_supplier_category
            FOREIGN KEY (category_id) REFERENCES supplier_categories(id) ON DELETE SET NULL;
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.STATISTICS
                   WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='suppliers'
                     AND INDEX_NAME='uq_supplier_external_ref') THEN
        ALTER TABLE suppliers ADD UNIQUE KEY uq_supplier_external_ref (organization_id, external_ref);
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.STATISTICS
                   WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='suppliers'
                     AND INDEX_NAME='idx_suppliers_not_deleted') THEN
        ALTER TABLE suppliers ADD INDEX idx_suppliers_not_deleted (organization_id, deleted_at);
    END IF;
END //
DELIMITER ;
CALL _mig033();
DROP PROCEDURE IF EXISTS _mig033;

-- ROLLBACK (manuale):
-- ALTER TABLE suppliers
--   DROP FOREIGN KEY fk_supplier_category,
--   DROP INDEX uq_supplier_external_ref,
--   DROP INDEX idx_suppliers_not_deleted,
--   DROP COLUMN category_id,
--   DROP COLUMN external_ref,
--   DROP COLUMN source;
-- -- NB: NON droppare deleted_at (di proprieta della mig 006).
