"""Links between cached Forgejo issues and Pipeline tasks."""

from __future__ import annotations

from datetime import datetime
from uuid import UUID, uuid4

from sqlalchemy import UniqueConstraint
from sqlmodel import Field

from app.core.time import utcnow
from app.models.tenancy import TenantScoped

RUNTIME_ANNOTATION_TYPES = (datetime,)


class ForgejoIssueTaskLink(TenantScoped, table=True):
    """Board-scoped Pipeline task created from a cached Forgejo issue."""

    __tablename__ = "forgejo_issue_task_links"  # pyright: ignore[reportAssignmentType]
    __table_args__ = (
        UniqueConstraint(
            "board_id",
            "issue_id",
            name="uq_forgejo_issue_task_links_board_issue",
        ),
        UniqueConstraint(
            "task_id",
            name="uq_forgejo_issue_task_links_task",
        ),
    )

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    organization_id: UUID = Field(foreign_key="organizations.id", index=True)
    board_id: UUID = Field(foreign_key="boards.id", index=True)
    issue_id: UUID = Field(foreign_key="forgejo_issues.id", index=True)
    task_id: UUID = Field(foreign_key="tasks.id", index=True)
    created_by_user_id: UUID | None = Field(default=None, foreign_key="users.id", index=True)
    created_at: datetime = Field(default_factory=utcnow)
