"""مدل User: کاربران ثبت‌نام‌شده از طریق OTP."""
from __future__ import annotations

import uuid

from sqlalchemy import Boolean, Enum as SAEnum
from sqlalchemy import ForeignKey, Index, String
from sqlalchemy.orm import Mapped, mapped_column

from app.core.database import Base
from app.models.base import TimestampMixin, UUIDPrimaryKeyMixin
from app.models.enums import UserRole, UserStatus
from app.models.types import GUID


class User(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "users"

    mobile: Mapped[str] = mapped_column(String(15), nullable=False, unique=True)
    keycloak_sub: Mapped[str | None] = mapped_column(String(100), nullable=True, unique=True)
    email: Mapped[str | None] = mapped_column(String(255), nullable=True)
    mobile_verified: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    role: Mapped[UserRole] = mapped_column(
        SAEnum(
            UserRole,
            name="user_role",
            values_callable=lambda enum_cls: [item.value for item in enum_cls],
        ),
        default=UserRole.PENDING_TENANT_ADMIN,
        nullable=False,
    )
    status: Mapped[UserStatus] = mapped_column(
        SAEnum(
            UserStatus,
            name="user_status",
            values_callable=lambda enum_cls: [item.value for item in enum_cls],
        ),
        default=UserStatus.ACTIVE,
        nullable=False,
    )
    # tenant انتخاب‌شده جاری کاربر (برای پشتیبانی چندtenant در آینده).
    current_tenant_id: Mapped[uuid.UUID | None] = mapped_column(
        GUID(), ForeignKey("tenants.id", ondelete="SET NULL"), nullable=True
    )

    __table_args__ = (
        Index("ix_users_mobile", "mobile", unique=True),
        Index("ix_users_keycloak_sub", "keycloak_sub", unique=True),
        Index("ix_users_status", "status"),
    )

    def __repr__(self) -> str:  # pragma: no cover
        return f"<User id={self.id} mobile={self.mobile!r} role={self.role}>"
