"""Public domain check API (no auth required)."""
from datetime import datetime

from fastapi import APIRouter, HTTPException, status

from app.schemas.domain import DomainCheckRequest, DomainCheckResponse
from app.services.domain_checker import domain_checker

router = APIRouter()


@router.post("", response_model=DomainCheckResponse)
async def check_domain_availability(request: DomainCheckRequest):
    """
    Check if a domain is available.
    
    This endpoint is public and does not require authentication.
    For quick checks, set `quick=true` to use DNS-only lookup (faster but less detailed).
    """
    # Validate domain format
    is_valid, error = domain_checker.validate_domain(request.domain)
    if not is_valid:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=error,
        )
    
    # Check domain
    result = await domain_checker.check_domain(request.domain, quick=request.quick)
    
    return DomainCheckResponse(
        domain=result.domain,
        status=result.status.value,
        is_available=result.is_available,
        registrar=result.registrar,
        expiration_date=result.expiration_date,
        creation_date=result.creation_date,
        name_servers=result.name_servers,
        error_message=result.error_message,
        checked_at=datetime.utcnow(),
    )


@router.get("/{domain}", response_model=DomainCheckResponse)
async def check_domain_get(domain: str, quick: bool = False):
    """
    Check domain availability via GET request.
    
    Useful for quick lookups. Domain should be URL-encoded if it contains special characters.
    """
    # Validate domain format
    is_valid, error = domain_checker.validate_domain(domain)
    if not is_valid:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=error,
        )
    
    # Check domain
    result = await domain_checker.check_domain(domain, quick=quick)
    
    return DomainCheckResponse(
        domain=result.domain,
        status=result.status.value,
        is_available=result.is_available,
        registrar=result.registrar,
        expiration_date=result.expiration_date,
        creation_date=result.creation_date,
        name_servers=result.name_servers,
        error_message=result.error_message,
        checked_at=datetime.utcnow(),
    )

