from __future__ import annotations

from datetime import date, datetime

from sqlalchemy import BigInteger, Date, DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.models.base import Base, SoftDeleteMixin, TimestampMixin


PRIMARY_KEY_TYPE = BigInteger().with_variant(Integer, "sqlite")


class User(Base, TimestampMixin, SoftDeleteMixin):
    __tablename__ = "sys_user"

    id: Mapped[int] = mapped_column(PRIMARY_KEY_TYPE, primary_key=True, autoincrement=True)
    phone: Mapped[str] = mapped_column(String(20), unique=True, index=True, nullable=False)
    name: Mapped[str] = mapped_column(String(50), nullable=False)
    nickname: Mapped[str | None] = mapped_column(String(50), nullable=True)
    registration_source: Mapped[str] = mapped_column(String(30), default="direct", nullable=False)
    registration_client_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, index=True)
    status: Mapped[int] = mapped_column(default=1, nullable=False)
    daily_chat_limit: Mapped[int] = mapped_column(Integer, default=100, nullable=False)
    daily_chat_used: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    daily_chat_reset_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    effective_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    expired_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    last_login_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    knowledge_permissions: Mapped[list["UserKnowledgePermission"]] = relationship(
        "UserKnowledgePermission", back_populates="user"
    )
    chat_sessions: Mapped[list["ChatSession"]] = relationship("ChatSession", back_populates="user")
