"""APIهای مدیریت و resolve دامنه."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db
from app.core.security import require_authenticated, require_tenant_admin
from app.schemas.domain import (
    DomainCreate,
    DomainRead,
    DomainResolveRequest,
    DomainResolveResponse,
)
from app.services.domain_service import DomainService
from app.services.tenant_service import TenantService

router = APIRouter(tags=["domains"])


@router.post(
    "/tenants/{tenant_id}/domains",
    response_model=DomainRead,
    status_code=status.HTTP_201_CREATED,
)
async def create_domain(
    tenant_id: UUID,
    payload: DomainCreate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_tenant_admin),
) -> DomainRead:
    domain = await DomainService(db).create(tenant_id, payload)
    return DomainRead.model_validate(domain)


@router.get("/tenants/{tenant_id}/domains", response_model=list[DomainRead])
async def list_domains(
    tenant_id: UUID,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_authenticated),
) -> list[DomainRead]:
    domains = await DomainService(db).list_by_tenant(tenant_id)
    return [DomainRead.model_validate(d) for d in domains]


@router.post("/domains/resolve", response_model=DomainResolveResponse)
async def resolve_domain(
    payload: DomainResolveRequest, db: AsyncSession = Depends(get_db)
) -> DomainResolveResponse:
    domain = await DomainService(db).resolve(payload.domain)
    tenant = await TenantService(db).get(domain.tenant_id)
    return DomainResolveResponse(
        tenant_id=tenant.id,
        tenant_slug=tenant.slug,
        domain=domain.domain,
        is_verified=domain.is_verified,
    )
