"""مدل Tenant: مستأجر اصلی پلتفرم."""
from __future__ import annotations

import uuid

from sqlalchemy import Boolean
from sqlalchemy import Enum as SAEnum
from sqlalchemy import 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 TenantStatus
from app.models.types import GUID


class Tenant(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "tenants"

    name: Mapped[str] = mapped_column(String(255), nullable=False)
    # slug یکتا برای تشخیص tenant (مثلاً در subdomain).
    slug: Mapped[str] = mapped_column(String(100), nullable=False, unique=True)
    status: Mapped[TenantStatus] = mapped_column(
        SAEnum(TenantStatus, name="tenant_status"),
        default=TenantStatus.ACTIVE,
        nullable=False,
    )
    # شناسه کاربر مالک (از Identity Service آینده؛ اینجا فقط ذخیره می‌شود).
    owner_user_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)

    # ---- پروفایل/تنظیمات tenant (فاز onboarding) ----
    business_type: Mapped[str | None] = mapped_column(String(100), nullable=True)
    default_locale: Mapped[str] = mapped_column(String(20), default="fa-IR", nullable=False)
    timezone: Mapped[str] = mapped_column(String(50), default="Asia/Tehran", nullable=False)
    primary_color: Mapped[str | None] = mapped_column(String(20), nullable=True)
    secondary_color: Mapped[str | None] = mapped_column(String(20), nullable=True)
    logo_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
    favicon_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
    onboarding_completed: Mapped[bool] = mapped_column(
        Boolean, default=False, nullable=False
    )

    __table_args__ = (
        Index("ix_tenants_slug", "slug", unique=True),
        Index("ix_tenants_status", "status"),
    )

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