"""Jira integration models — link Aegis entities to Jira issues."""

import enum
import uuid
from sqlalchemy import Column, String, DateTime, ForeignKey, Enum as SQLEnum, Index, func
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.orm import relationship

from app.database import Base


class JiraLinkEntityType(str, enum.Enum):
    test = "test"
    technique = "technique"
    campaign = "campaign"
    evidence = "evidence"


class JiraSyncDirection(str, enum.Enum):
    aegis_to_jira = "aegis_to_jira"
    jira_to_aegis = "jira_to_aegis"
    bidirectional = "bidirectional"


class JiraLink(Base):
    """Associates an Aegis entity with a Jira issue for bidirectional sync."""

    __tablename__ = "jira_links"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    entity_type = Column(SQLEnum(JiraLinkEntityType), nullable=False)
    entity_id = Column(UUID(as_uuid=True), nullable=False)
    jira_issue_key = Column(String(50), nullable=False)
    jira_issue_id = Column(String(50))
    jira_project_key = Column(String(20))
    jira_status = Column(String(100))
    jira_priority = Column(String(50))
    jira_assignee = Column(String(255))
    jira_story_points = Column(String(10))
    sync_direction = Column(
        SQLEnum(JiraSyncDirection), default=JiraSyncDirection.bidirectional
    )
    last_synced_at = Column(DateTime)
    sync_metadata = Column(JSONB, default={})
    created_by = Column(UUID(as_uuid=True), ForeignKey("users.id"))
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())

    creator = relationship("User", foreign_keys=[created_by])

    __table_args__ = (
        Index("ix_jira_links_entity_id", "entity_id"),
        Index("ix_jira_links_issue_key", "jira_issue_key"),
        Index("ix_jira_links_entity_type_entity_id", "entity_type", "entity_id"),
    )
