"""مدل Domain: دامنه‌ها/زیردامنه‌های هر tenant."""
from __future__ import annotations

import uuid
from datetime import datetime

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

from app.core.database import Base
from app.models.base import UUIDPrimaryKeyMixin
from app.models.enums import DomainType, DomainVerificationStatus
from app.models.types import GUID


class Domain(UUIDPrimaryKeyMixin, Base):
    __tablename__ = "domains"

    tenant_id: Mapped[uuid.UUID] = mapped_column(
        GUID(), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False
    )
    # دامنه به‌صورت یکتا در کل پلتفرم (مثلاً acme.example.com یا shop.acme.ir).
    domain: Mapped[str] = mapped_column(String(255), nullable=False, unique=True)
    domain_type: Mapped[DomainType] = mapped_column(
        SAEnum(DomainType, name="domain_type"),
        default=DomainType.SUBDOMAIN,
        nullable=False,
    )
    is_verified: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    verified_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    # آیا این دامنه، دامنه اصلی/پیش‌فرض tenant است (مثلاً زیردامنه ساخته‌شده در onboarding).
    is_primary: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    verification_status: Mapped[DomainVerificationStatus] = mapped_column(
        SAEnum(
            DomainVerificationStatus,
            name="domain_verification_status",
            values_callable=lambda enum_cls: [item.value for item in enum_cls],
        ),
        default=DomainVerificationStatus.PENDING,
        nullable=False,
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), nullable=False
    )

    __table_args__ = (
        Index("ix_domains_domain", "domain", unique=True),
        Index("ix_domains_tenant_id", "tenant_id"),
    )

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