-- ============================================================================
-- Migration 028 - Policy attestation + versioning (P3 policy management)
-- ----------------------------------------------------------------------------
--   policy_versions:     snapshot del contenuto ad ogni approvazione (per diff/storico)
--   policy_attestations: presa visione del dipendente di una specifica versione
--
-- Idempotente. Rilanciabile.
--   mysql -h localhost nis2_agile_db -e "source docs/sql/028_policy_attestation_versioning.sql"
-- ============================================================================

CREATE TABLE IF NOT EXISTS policy_versions (
    id              INT NOT NULL AUTO_INCREMENT,
    policy_id       INT NOT NULL,
    organization_id INT NOT NULL,
    version         VARCHAR(20) NOT NULL,
    content         LONGTEXT NULL COMMENT 'Snapshot contenuto policy alla versione',
    change_note     VARCHAR(255) NULL,
    created_by      INT NULL,
    created_at      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_pv_policy (policy_id),
    KEY idx_pv_org (organization_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Storico versioni policy per diff e tracciabilita';

CREATE TABLE IF NOT EXISTS policy_attestations (
    id              INT NOT NULL AUTO_INCREMENT,
    policy_id       INT NOT NULL,
    organization_id INT NOT NULL,
    user_id         INT NOT NULL,
    version         VARCHAR(20) NOT NULL COMMENT 'Versione della policy attestata',
    attested_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    ip_address      VARCHAR(45) NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uq_att (policy_id, user_id, version),
    KEY idx_att_policy (policy_id),
    KEY idx_att_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Presa visione (attestation) policy da parte dei dipendenti';

-- ROLLBACK:
-- DROP TABLE IF EXISTS policy_attestations;
-- DROP TABLE IF EXISTS policy_versions;
