"""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
import uuid

# Import Boolean, Column, ForeignKey, Index, UniqueConst... from sqlalchemy
from sqlalchemy import Boolean, Column, ForeignKey, Index, UniqueConstraint

# Import UUID from sqlalchemy.dialects.postgresql
from sqlalchemy.dialects.postgresql import UUID

# Import relationship from sqlalchemy.orm
from sqlalchemy.orm import relationship

# Import Base from app.database
from app.database import Base


# Define class TestTemplateDetectionRule
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.
    """
    # Assign __tablename__ = "test_template_detection_rules"
    __tablename__ = "test_template_detection_rules"

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

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

    # Assign __table_args__ = (
    __table_args__ = (
        Index('ix_ttdr_template', 'test_template_id'),
        Index('ix_ttdr_rule', 'detection_rule_id'),
        UniqueConstraint(
            # Literal argument value
            'test_template_id', 'detection_rule_id',
            # Keyword argument: name
            name='uq_template_detection_rule',
        ),
    )
