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

from app.core.database import Base


class UserRole(str, Enum):
    USER = "user"
    ADMIN = "admin"


class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    login: Mapped[str] = mapped_column(String(50), unique=True, nullable=False, index=True)
    password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
    nickname: Mapped[str] = mapped_column(String(50), nullable=False)
    avatar_path: Mapped[str | None] = mapped_column(String(500), nullable=True)
    telegram_id: Mapped[int | None] = mapped_column(BigInteger, unique=True, nullable=True)
    telegram_username: Mapped[str | None] = mapped_column(String(50), nullable=True)
    role: Mapped[str] = mapped_column(String(20), default=UserRole.USER.value)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    # Relationships
    created_marathons: Mapped[list["Marathon"]] = relationship(
        "Marathon",
        back_populates="creator",
        foreign_keys="Marathon.creator_id"
    )
    participations: Mapped[list["Participant"]] = relationship(
        "Participant",
        back_populates="user"
    )
    proposed_games: Mapped[list["Game"]] = relationship(
        "Game",
        back_populates="proposed_by",
        foreign_keys="Game.proposed_by_id"
    )
    approved_games: Mapped[list["Game"]] = relationship(
        "Game",
        back_populates="approved_by",
        foreign_keys="Game.approved_by_id"
    )

    @property
    def is_admin(self) -> bool:
        return self.role == UserRole.ADMIN.value

    @property
    def avatar_url(self) -> str | None:
        if self.avatar_path:
            return f"/uploads/avatars/{self.avatar_path.split('/')[-1]}"
        return None
