"""Cached Forgejo issue model for storing issue data locally."""

from __future__ import annotations

from datetime import datetime
from uuid import UUID, uuid4

import sqlalchemy as sa
from sqlalchemy import JSON, Column
from sqlmodel import Field, Index, SQLModel

from app.core.time import utcnow

RUNTIME_ANNOTATION_TYPES = (datetime,)


class ForgejoIssue(SQLModel, table=True):
    """Cached Forgejo issue stored from remote repository."""

    __tablename__ = "forgejo_issues"  # pyright: ignore[reportAssignmentType]

    id: UUID = Field(default_factory=uuid4, primary_key=True)
    organization_id: UUID = Field(foreign_key="organizations.id", index=True)
    repository_id: UUID = Field(foreign_key="forgejo_repositories.id", index=True)
    forgejo_issue_number: int = Field(index=True)

    title: str
    body: str | None = Field(default=None, sa_column=Column(sa.Text, nullable=True))
    body_preview: str | None = Field(default=None, max_length=1000)
    state: str = Field(default="open")
    is_pull_request: bool = Field(default=False)

    # JSON fields for complex data
    labels: list[dict[str, object]] = Field(default_factory=list, sa_column=Column(JSON))
    assignees: list[dict[str, object]] = Field(default_factory=list, sa_column=Column(JSON))
    milestone: dict[str, object] | None = Field(default=None, sa_column=Column(JSON, nullable=True))

    author: str
    html_url: str
    forgejo_created_at: datetime
    forgejo_updated_at: datetime
    forgejo_closed_at: datetime | None = Field(default=None)

    last_synced_at: datetime = Field(default_factory=utcnow)

    created_at: datetime = Field(default_factory=utcnow)
    updated_at: datetime = Field(default_factory=utcnow)

    __table_args__ = (
        Index(
            "ix_forgejo_issues_repo_number", "repository_id", "forgejo_issue_number", unique=True
        ),
    )
