"""add_unique_test_detection_result

Enforce one evaluation per (test, detection_rule) pair.  Before creating
the constraint, duplicate rows (if any) are collapsed so the migration
never fails on an existing database.

Revision ID: b025uqtdr
Revises: b024critidx
Create Date: 2026-02-18 14:00:00.000000

"""
from typing import Sequence, Union

from alembic import op

revision: str = "b025uqtdr"
down_revision: Union[str, None] = "b024critidx"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Remove duplicates keeping the most recently evaluated row
    op.execute("""
        DELETE FROM test_detection_results
        WHERE id NOT IN (
            SELECT DISTINCT ON (test_id, detection_rule_id) id
            FROM test_detection_results
            ORDER BY test_id, detection_rule_id, evaluated_at DESC NULLS LAST
        )
    """)

    op.create_unique_constraint(
        "uq_tdr_test_rule",
        "test_detection_results",
        ["test_id", "detection_rule_id"],
    )


def downgrade() -> None:
    op.drop_constraint("uq_tdr_test_rule", "test_detection_results", type_="unique")
