"""اسکیما و endpoint عمومی سایت tenant (بدون نیاز به لاگین)."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db
from app.models.enums import TenantStatus
from app.repositories.tenant import DomainRepository, TenantRepository
from shared.exceptions import NotFoundError

router = APIRouter(prefix="/public", tags=["public"])


class PublicTenantSiteRead(BaseModel):
    """اطلاعات عمومی قابل نمایش روی ساب‌دامین tenant."""

    tenant_id: UUID
    name: str
    slug: str
    status: TenantStatus
    business_type: str | None = None
    primary_color: str | None = None
    secondary_color: str | None = None
    logo_url: str | None = None
    favicon_url: str | None = None
    primary_domain: str | None = None
    tagline: str = Field(default="روی پلتفرم تربت‌یار")


@router.get("/tenant-site", response_model=PublicTenantSiteRead)
async def get_public_tenant_site(
    request: Request,
    db: AsyncSession = Depends(get_db),
) -> PublicTenantSiteRead:
    """Resolve سایت tenant از روی Host (middleware) یا ?slug=."""
    tenant_id = getattr(request.state, "tenant_id", None)
    tenant_slug = getattr(request.state, "tenant_slug", None)
    query_slug = (request.query_params.get("slug") or "").strip().lower() or None

    tenant_repo = TenantRepository(db)
    domain_repo = DomainRepository(db)
    tenant = None
    if tenant_id is not None:
        tenant = await tenant_repo.get(tenant_id)
    elif tenant_slug:
        tenant = await tenant_repo.get_by_slug(tenant_slug)
    elif query_slug:
        tenant = await tenant_repo.get_by_slug(query_slug)

    if tenant is None:
        raise NotFoundError("سایت این دامنه یافت نشد یا هنوز فعال نشده است")

    if tenant.status in {TenantStatus.SUSPENDED, TenantStatus.ARCHIVED}:
        raise NotFoundError("این workspace در حال حاضر در دسترس نیست")

    domains = await domain_repo.list_by_tenant(tenant.id)
    primary = next((d for d in domains if d.is_primary), None)
    if primary is None and domains:
        primary = domains[0]

    return PublicTenantSiteRead(
        tenant_id=tenant.id,
        name=tenant.name,
        slug=tenant.slug,
        status=tenant.status,
        business_type=tenant.business_type,
        primary_color=tenant.primary_color,
        secondary_color=tenant.secondary_color,
        logo_url=tenant.logo_url,
        favicon_url=tenant.favicon_url,
        primary_domain=primary.domain if primary else None,
    )
