"""TestTemplateDetectionRule — links test templates to detection rules.

Enables the Blue Team to see which detection rules should fire
for a given test template / attack procedure.
"""

import uuid
from datetime import datetime

from sqlalchemy import Column, Boolean, ForeignKey, Index, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship

from app.database import Base


class TestTemplateDetectionRule(Base):
    """
    Association between a test template and a detection rule.

    Auto-generated by matching mitre_technique_id, or manually curated.
    ``is_primary`` marks rules with severity >= high as primary detections.
    """
    __tablename__ = "test_template_detection_rules"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    test_template_id = Column(
        UUID(as_uuid=True),
        ForeignKey("test_templates.id", ondelete="CASCADE"),
        nullable=True,
    )
    detection_rule_id = Column(
        UUID(as_uuid=True),
        ForeignKey("detection_rules.id", ondelete="CASCADE"),
        nullable=False,
    )
    is_primary = Column(Boolean, default=False)

    # Relationships
    test_template = relationship("TestTemplate")
    detection_rule = relationship("DetectionRule")

    __table_args__ = (
        Index('ix_ttdr_template', 'test_template_id'),
        Index('ix_ttdr_rule', 'detection_rule_id'),
        UniqueConstraint(
            'test_template_id', 'detection_rule_id',
            name='uq_template_detection_rule',
        ),
    )
