"""Domain schemas."""
from datetime import datetime
from typing import Optional, List

from pydantic import BaseModel, Field, field_validator

from app.models.domain import DomainStatus


class DomainCreate(BaseModel):
    """Schema for adding a domain to monitoring list."""
    name: str = Field(..., min_length=4, max_length=255)
    notify_on_available: bool = True
    
    @field_validator('name')
    @classmethod
    def validate_domain_name(cls, v: str) -> str:
        """Validate and normalize domain name."""
        v = v.lower().strip()
        if v.startswith('http://'):
            v = v[7:]
        elif v.startswith('https://'):
            v = v[8:]
        if v.startswith('www.'):
            v = v[4:]
        v = v.split('/')[0]
        
        if '.' not in v:
            raise ValueError('Domain must include TLD (e.g., .com)')
        
        return v


class DomainResponse(BaseModel):
    """Schema for domain response."""
    id: int
    name: str
    status: DomainStatus
    is_available: bool
    registrar: Optional[str]
    expiration_date: Optional[datetime]
    notify_on_available: bool
    created_at: datetime
    last_checked: Optional[datetime]
    
    class Config:
        from_attributes = True


class DomainCheckRequest(BaseModel):
    """Schema for quick domain availability check."""
    domain: str = Field(..., min_length=4, max_length=255)
    quick: bool = False  # If True, only DNS check (faster)
    
    @field_validator('domain')
    @classmethod
    def validate_domain(cls, v: str) -> str:
        """Validate and normalize domain."""
        v = v.lower().strip()
        if v.startswith('http://'):
            v = v[7:]
        elif v.startswith('https://'):
            v = v[8:]
        if v.startswith('www.'):
            v = v[4:]
        v = v.split('/')[0]
        return v


class DomainCheckResponse(BaseModel):
    """Schema for domain check response."""
    domain: str
    status: str
    is_available: bool
    registrar: Optional[str] = None
    expiration_date: Optional[datetime] = None
    creation_date: Optional[datetime] = None
    name_servers: Optional[List[str]] = None
    error_message: Optional[str] = None
    checked_at: datetime


class DomainListResponse(BaseModel):
    """Schema for paginated domain list."""
    domains: List[DomainResponse]
    total: int
    page: int
    per_page: int
    pages: int


class ExpiryUpdate(BaseModel):
    """Schema for manually setting domain expiration date."""
    expiration_date: Optional[datetime] = None
    
    class Config:
        json_schema_extra = {
            "example": {
                "expiration_date": "2025-12-31T00:00:00Z"
            }
        }

