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

from uuid import UUID

from pydantic import BaseModel, Field, field_validator

from app.models.enums import MembershipStatus, TenantMembershipRole, TenantStatus
from app.schemas.domain import DomainRead
from app.schemas.tenant import SLUG_PATTERN, TenantRead


class OnboardingTenantCreate(BaseModel):
    """گام ۱ onboarding: ایجاد tenant توسط کاربر جاری."""

    business_name: str = Field(..., min_length=1, max_length=255)
    slug: str = Field(..., min_length=1, max_length=100)
    business_type: str | None = Field(default=None, max_length=100)
    default_locale: str = Field(default="fa-IR", max_length=20)
    timezone: str = Field(default="Asia/Tehran", max_length=50)

    @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


class OnboardingBrandingUpdate(BaseModel):
    """گام ۲ onboarding: برندینگ."""

    primary_color: str | None = Field(default=None, max_length=20)
    secondary_color: str | None = Field(default=None, max_length=20)
    logo_url: str | None = Field(default=None, max_length=500)
    favicon_url: str | None = Field(default=None, max_length=500)


class OnboardingDomainUpdate(BaseModel):
    """گام ۳ onboarding: دامنه اختصاصی (زیردامنه به‌صورت خودکار از slug ساخته می‌شود)."""

    custom_domain: str | None = Field(default=None, max_length=255)

    @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 MembershipSummary(BaseModel):
    tenant_id: UUID
    tenant_name: str
    tenant_slug: str
    tenant_status: TenantStatus
    onboarding_completed: bool
    role: TenantMembershipRole
    status: MembershipStatus
    is_owner: bool


class MeResponse(BaseModel):
    user_id: UUID
    mobile: str
    email: str | None
    platform_role: str
    onboarding_required: bool
    current_tenant_id: UUID | None
    memberships: list[MembershipSummary]


class TenantContextRead(BaseModel):
    tenant: TenantRead
    role: TenantMembershipRole | None = None
    is_owner: bool = False
    plan_code: str | None = None
    plan_name: str | None = None
    subscription_status: str | None = None
    domains: list[DomainRead] = Field(default_factory=list)
    primary_domain: str | None = None


class TenantSwitchRequest(BaseModel):
    tenant_id: UUID
