from datetime import datetime
from enum import Enum
from sqlalchemy import String, DateTime, ForeignKey, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base


class GameStatus(str, Enum):
    PENDING = "pending"      # Предложена участником, ждёт модерации
    APPROVED = "approved"    # Одобрена организатором
    REJECTED = "rejected"    # Отклонена


class Game(Base):
    __tablename__ = "games"

    id: Mapped[int] = mapped_column(primary_key=True)
    marathon_id: Mapped[int] = mapped_column(ForeignKey("marathons.id", ondelete="CASCADE"), index=True)
    title: Mapped[str] = mapped_column(String(100), nullable=False)
    cover_path: Mapped[str | None] = mapped_column(String(500), nullable=True)
    download_url: Mapped[str] = mapped_column(Text, nullable=False)
    genre: Mapped[str | None] = mapped_column(String(50), nullable=True)
    status: Mapped[str] = mapped_column(String(20), default=GameStatus.PENDING.value)
    proposed_by_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    approved_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    # Relationships
    marathon: Mapped["Marathon"] = relationship("Marathon", back_populates="games")
    proposed_by: Mapped["User"] = relationship(
        "User",
        back_populates="proposed_games",
        foreign_keys=[proposed_by_id]
    )
    approved_by: Mapped["User | None"] = relationship(
        "User",
        back_populates="approved_games",
        foreign_keys=[approved_by_id]
    )
    challenges: Mapped[list["Challenge"]] = relationship(
        "Challenge",
        back_populates="game",
        cascade="all, delete-orphan"
    )

    @property
    def is_approved(self) -> bool:
        return self.status == GameStatus.APPROVED.value

    @property
    def is_pending(self) -> bool:
        return self.status == GameStatus.PENDING.value
