"""اسکیماهای Tenant."""
from __future__ import annotations

import re
from datetime import datetime
from uuid import UUID

from pydantic import BaseModel, Field, field_validator

from app.models.enums import TenantStatus
from app.schemas.common import ORMModel

SLUG_PATTERN = re.compile(r"^[a-z0-9]([a-z0-9-]{0,98}[a-z0-9])?$")


class TenantCreate(BaseModel):
    name: str = Field(..., min_length=1, max_length=255)
    slug: str = Field(..., min_length=1, max_length=100)
    owner_user_id: UUID | None = None
    custom_domain: str | None = Field(default=None, max_length=255)

    @field_validator("slug")
    @classmethod
    def validate_slug(cls, value: str) -> str:
        value = value.strip().lower()
        if not SLUG_PATTERN.match(value):
            raise ValueError(
                "slug باید فقط شامل حروف کوچک انگلیسی، اعداد و خط تیره باشد"
            )
        return value

    @field_validator("custom_domain")
    @classmethod
    def normalize_domain(cls, value: str | None) -> str | None:
        if value is None or not value.strip():
            return None
        return value.strip().lower()


class AdminTenantCreate(BaseModel):
    """ایجاد tenant توسط کاربر احراز هویت‌شده (مالک = کاربر جاری)."""

    name: str = Field(..., min_length=1, max_length=255)
    slug: str = Field(..., min_length=1, max_length=100)
    custom_domain: str | None = Field(default=None, max_length=255)

    @field_validator("slug")
    @classmethod
    def validate_slug(cls, value: str) -> str:
        return TenantCreate.validate_slug(value)

    @field_validator("custom_domain")
    @classmethod
    def normalize_domain(cls, value: str | None) -> str | None:
        return TenantCreate.normalize_domain(value)


class TenantUpdate(BaseModel):
    name: str | None = Field(default=None, min_length=1, max_length=255)
    status: TenantStatus | None = None
    owner_user_id: UUID | None = None


class TenantRead(ORMModel):
    id: UUID
    name: str
    slug: str
    status: TenantStatus
    owner_user_id: UUID | None
    business_type: str | None = None
    default_locale: str = "fa-IR"
    timezone: str = "Asia/Tehran"
    primary_color: str | None = None
    secondary_color: str | None = None
    logo_url: str | None = None
    favicon_url: str | None = None
    onboarding_completed: bool = False
    created_at: datetime
    updated_at: datetime
