from datetime import date, datetime
from typing import Optional

from sqlalchemy import func, ForeignKey, DateTime
from sqlalchemy.orm import mapped_column, Mapped, relationship

from app.database import Base


class Users(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str]
    username: Mapped[str]
    hashed_password: Mapped[str]
    role: Mapped[int] = mapped_column(server_default=f'0')
    black_phoenix: Mapped[bool] = mapped_column(server_default='false')
    avatar_image: Mapped[Optional[str]] = mapped_column(
        server_default='https://images.black-phoenix.ru/static/images/%D1%82%D1%8B%20%D1%83%D0%B6%D0%B5%20%D0%BF%D0%B5%D1%88%D0%BA%D0%B0%20BP.png')
    date_of_birth: Mapped[date]
    date_of_registration: Mapped[date] = mapped_column(server_default=func.now())

    message = relationship("Messages", back_populates="user")
    usersxchats = relationship("UsersXChats", back_populates="user")
    chat = relationship("Chats", primaryjoin='Chats.chat_for == Users.id', back_populates="user_to_exclude")
    creator = relationship("Chats", primaryjoin='Chats.created_by == Users.id', back_populates="user_who_create")
    verificationcode = relationship("UsersVerificationCodes", back_populates="user")

    def __str__(self):
        return f"Юзер {self.username}"


class UsersVerificationCodes(Base):
    __tablename__ = "usersverificationcodes"

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    code: Mapped[str]
    description: Mapped[str]
    date_of_creation: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    user = relationship("Users", back_populates="verificationcode")

    def __str__(self):
        return f"Код {self.code} для юзера {self.user_id}. {self.description}"
