-- ═══════════════════════════════════════════════════════════════════
-- NIS2 Agile - Migration 004: Non-Conformity & CAPA
-- Tabelle per gestione non conformità e azioni correttive
-- Predisposizione integrazione SistemiG.agile
-- ═══════════════════════════════════════════════════════════════════

-- Non-Conformity Reports (NCR)
CREATE TABLE IF NOT EXISTS non_conformities (
    id INT AUTO_INCREMENT PRIMARY KEY,
    organization_id INT NOT NULL,
    ncr_code VARCHAR(20) NOT NULL,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    source ENUM(
        'assessment', 'audit', 'incident', 'supplier_review',
        'management_review', 'external_audit', 'other'
    ) NOT NULL DEFAULT 'assessment',
    -- Link to source entity
    source_entity_type VARCHAR(50),
    source_entity_id INT,
    -- Classification
    severity ENUM('minor', 'major', 'critical', 'observation') NOT NULL DEFAULT 'minor',
    category VARCHAR(100),
    nis2_article VARCHAR(20),
    -- Lifecycle
    status ENUM(
        'open', 'investigating', 'action_planned',
        'correcting', 'verifying', 'closed', 'cancelled'
    ) NOT NULL DEFAULT 'open',
    -- Ownership
    identified_by INT,
    assigned_to INT,
    -- Dates
    identified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    target_close_date DATE,
    actual_close_date DATE,
    -- Root Cause Analysis
    root_cause_analysis TEXT,
    root_cause_method ENUM('five_whys', 'fishbone', 'fta', 'other'),
    -- External integration (SistemiG.agile)
    external_system VARCHAR(50),
    external_id VARCHAR(100),
    external_synced_at DATETIME,
    -- Metadata
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE,
    FOREIGN KEY (identified_by) REFERENCES users(id) ON DELETE SET NULL,
    FOREIGN KEY (assigned_to) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_ncr_org (organization_id),
    INDEX idx_ncr_status (status),
    INDEX idx_ncr_severity (severity),
    INDEX idx_ncr_source (source_entity_type, source_entity_id),
    INDEX idx_ncr_external (external_system, external_id),
    UNIQUE KEY uk_org_ncr_code (organization_id, ncr_code)
) ENGINE=InnoDB;

-- Corrective and Preventive Actions (CAPA)
CREATE TABLE IF NOT EXISTS capa_actions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ncr_id INT NOT NULL,
    organization_id INT NOT NULL,
    capa_code VARCHAR(20) NOT NULL,
    action_type ENUM('corrective', 'preventive', 'containment') NOT NULL DEFAULT 'corrective',
    title VARCHAR(255) NOT NULL,
    description TEXT,
    -- Lifecycle
    status ENUM('planned', 'in_progress', 'completed', 'verified', 'ineffective') NOT NULL DEFAULT 'planned',
    -- Ownership & Dates
    responsible_user_id INT,
    due_date DATE,
    completion_date DATE,
    verification_date DATE,
    verified_by INT,
    -- Effectiveness
    effectiveness_review TEXT,
    is_effective TINYINT(1),
    -- External integration (SistemiG.agile)
    external_system VARCHAR(50),
    external_id VARCHAR(100),
    -- Metadata
    notes TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (ncr_id) REFERENCES non_conformities(id) ON DELETE CASCADE,
    FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE,
    FOREIGN KEY (responsible_user_id) REFERENCES users(id) ON DELETE SET NULL,
    FOREIGN KEY (verified_by) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_capa_ncr (ncr_id),
    INDEX idx_capa_org (organization_id),
    INDEX idx_capa_status (status),
    INDEX idx_capa_due (due_date),
    UNIQUE KEY uk_org_capa_code (organization_id, capa_code)
) ENGINE=InnoDB;
