"""Add materialised priority_score + cpr_score columns for SQL sort

Revision ID: 024
Revises: 023
Create Date: 2026-05-25 13:00:00.000000

Until now `priority_score` and `cpr_score` were computed in Python from
`calculate_priority_breakdown()` at response time. The list endpoint
paginated FIRST in SQL then re-sorted only the current page by the
computed score — so "PRIO desc" looked correct row-by-row but pages 2+
were not in global order.

Tester reported: "Spaltensortierung gilt nur teilweise für die
aktuell angezeigten CVES."

Add two indexed columns. Forward-write paths (sync / enrich / override
/ manual edits) call `vuln.refresh_scores()` to keep them current.
Existing rows backfill via a one-off `recompute_all_scores()` admin
endpoint (or the nightly Vulnrichment + URS jobs which already touch
every open vuln).

Idempotent — ADD COLUMN IF NOT EXISTS.
"""
from alembic import op


revision = "024"
down_revision = "023"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.execute("""
        ALTER TABLE vulnerabilities
            ADD COLUMN IF NOT EXISTS priority_score DOUBLE PRECISION,
            ADD COLUMN IF NOT EXISTS cpr_score      DOUBLE PRECISION;
    """)
    op.execute("""
        CREATE INDEX IF NOT EXISTS ix_vulnerabilities_priority_score
            ON vulnerabilities (priority_score);
    """)
    op.execute("""
        CREATE INDEX IF NOT EXISTS ix_vulnerabilities_cpr_score
            ON vulnerabilities (cpr_score);
    """)


def downgrade() -> None:
    op.execute("DROP INDEX IF EXISTS ix_vulnerabilities_priority_score;")
    op.execute("DROP INDEX IF EXISTS ix_vulnerabilities_cpr_score;")
    op.execute("""
        ALTER TABLE vulnerabilities
            DROP COLUMN IF EXISTS priority_score,
            DROP COLUMN IF EXISTS cpr_score;
    """)
