import enum
import uuid

from sqlalchemy import ForeignKey, Integer, String, Text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from api.models.base import Base, TimestampMixin, new_uuid


class RepoGoalStatus(str, enum.Enum):
    active = "active"
    paused = "paused"
    completed = "completed"
    archived = "archived"


class RepoGoal(Base, TimestampMixin):
    __tablename__ = "repo_goals"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=new_uuid
    )
    repo_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("managed_repos.id", ondelete="RESTRICT"), nullable=False, index=True
    )
    domain_goal_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True), ForeignKey("domain_goals.id", ondelete="SET NULL"), nullable=True, index=True
    )
    title: Mapped[str] = mapped_column(String(500), nullable=False)
    description: Mapped[str] = mapped_column(Text, nullable=False)
    priority: Mapped[int] = mapped_column(Integer, nullable=False, default=100, server_default="100")
    status: Mapped[str] = mapped_column(
        String(20), nullable=False, default=RepoGoalStatus.active.value, server_default="active"
    )

    repo: Mapped["ManagedRepo"] = relationship(  # noqa: F821
        "ManagedRepo", back_populates="goals", lazy="selectin"
    )
    domain_goal: Mapped["DomainGoal"] = relationship(  # noqa: F821
        "DomainGoal", back_populates="repo_goals", lazy="selectin"
    )
    workplans: Mapped[list["Workplan"]] = relationship(  # noqa: F821
        "Workplan", back_populates="repo_goal", lazy="selectin"
    )

    @property
    def repo_slug(self) -> str:
        return self.repo.slug if self.repo is not None else ""
