-- ============================================================
-- NIS2 Agile - Migration 006: Security & Performance Improvements
-- Data: 2026-02-20
-- NOTA: Eseguire una sola volta. I CREATE INDEX falliscono se gia' esistono.
-- ============================================================

-- ── 1. Indici performance su incidents (NIS2 Art.23 deadlines) ────────────
CREATE INDEX idx_inc_org_status       ON incidents (organization_id, status);
CREATE INDEX idx_inc_org_significant  ON incidents (organization_id, is_significant);
CREATE INDEX idx_inc_early_warning    ON incidents (organization_id, early_warning_due);
CREATE INDEX idx_inc_notification     ON incidents (organization_id, notification_due);
CREATE INDEX idx_inc_final_report     ON incidents (organization_id, final_report_due);

-- ── 2. Indici performance su risks ────────────────────────────────────────
CREATE INDEX idx_risks_org_status ON risks (organization_id, status);
CREATE INDEX idx_risks_org_score  ON risks (organization_id, inherent_risk_score);

-- ── 3. Indici performance su audit_logs ───────────────────────────────────
CREATE INDEX idx_audit_org_ts   ON audit_logs (organization_id, created_at);
CREATE INDEX idx_audit_entity   ON audit_logs (entity_type, entity_id);

-- ── 4. Soft delete su tabelle critiche ────────────────────────────────────
ALTER TABLE risks
    ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMP NULL DEFAULT NULL AFTER updated_at;

ALTER TABLE policies
    ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMP NULL DEFAULT NULL AFTER updated_at;

ALTER TABLE suppliers
    ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMP NULL DEFAULT NULL AFTER updated_at;

-- Indici per soft delete
CREATE INDEX idx_risks_not_deleted    ON risks (organization_id, deleted_at);
CREATE INDEX idx_policies_not_deleted ON policies (organization_id, deleted_at);

-- ── 5. Indice su refresh_tokens per performance cleanup ───────────────────
CREATE INDEX idx_refresh_expires ON refresh_tokens (user_id, expires_at);

-- ── Fine migration ────────────────────────────────────────────────────────
SELECT 'Migration 006 completed' AS status;
