from datetime import datetime
from enum import Enum
from sqlalchemy import String, BigInteger, DateTime, Boolean, ForeignKey, Integer
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)
    telegram_first_name: Mapped[str | None] = mapped_column(String(100), nullable=True)
    telegram_last_name: Mapped[str | None] = mapped_column(String(100), nullable=True)
    telegram_avatar_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
    role: Mapped[str] = mapped_column(String(20), default=UserRole.USER.value)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    # Ban fields
    is_banned: Mapped[bool] = mapped_column(Boolean, default=False)
    banned_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    banned_until: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)  # None = permanent
    banned_by_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("users.id"), nullable=True)
    ban_reason: Mapped[str | None] = mapped_column(String(500), nullable=True)

    # 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"
    )
    banned_by: Mapped["User | None"] = relationship(
        "User",
        remote_side="User.id",
        foreign_keys=[banned_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:
            # Lazy import to avoid circular dependency
            from app.services.storage import storage_service
            return storage_service.get_url(self.avatar_path, "avatars")
        return None
