-- Migration : tables dashboard vulnérabilités Qualys
-- Aligné sur le DDL prod (PG 15.16) — idempotent
-- Référencé par : app/services/qualys_service.py (compute_vuln_dashboard, load_vuln_dashboard)

CREATE TABLE IF NOT EXISTS qualys_vuln_snapshot_run (
    id            SERIAL PRIMARY KEY,
    run_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    status        VARCHAR(20) NOT NULL DEFAULT 'pending',
    asset_count   INTEGER NOT NULL DEFAULT 0,
    duration_sec  INTEGER NOT NULL DEFAULT 0,
    msg           TEXT,
    triggered_by  VARCHAR(50)
);

CREATE INDEX IF NOT EXISTS idx_vuln_run_at
    ON qualys_vuln_snapshot_run (run_at DESC);

CREATE TABLE IF NOT EXISTS qualys_vuln_snapshot (
    id                SERIAL PRIMARY KEY,
    run_id            INTEGER NOT NULL REFERENCES qualys_vuln_snapshot_run(id) ON DELETE CASCADE,
    dimension         VARCHAR(20) NOT NULL,
    dimension_value   VARCHAR(100),
    dimension_value2  VARCHAR(100),
    total             INTEGER NOT NULL DEFAULT 0,
    critical          INTEGER NOT NULL DEFAULT 0,
    high              INTEGER NOT NULL DEFAULT 0,
    medium            INTEGER NOT NULL DEFAULT 0,
    sain              INTEGER NOT NULL DEFAULT 0,
    non_scanne        INTEGER NOT NULL DEFAULT 0
);

CREATE INDEX IF NOT EXISTS idx_vuln_snap_run_dim
    ON qualys_vuln_snapshot (run_id, dimension);
CREATE INDEX IF NOT EXISTS idx_vuln_snap_dim_val
    ON qualys_vuln_snapshot (dimension, dimension_value);
