from pydantic import BaseModel, Field, field_validator, ConfigDict
from typing import Optional
from datetime import datetime
from enum import Enum

class DocumentTypeEnum(str, Enum):
    VOUCHER = "voucher"
    TICKET = "ticket"
    INSURANCE = "insurance"
    PASSPORT = "passport"
    VISA = "visa"
    ITINERARY = "itinerary"
    INVOICE = "invoice"
    RECEIPT = "receipt"
    OTHER = "other"

class DocumentBase(BaseModel):
    booking_id: Optional[str] = None
    customer_id: Optional[str] = None
    document_type: DocumentTypeEnum
    file_name: str = Field(..., min_length=1, max_length=255)
    file_url: str = Field(..., min_length=1, max_length=500)
    file_size_kb: Optional[int] = Field(None, ge=0)
    mime_type: Optional[str] = Field(None, max_length=100)
    description: Optional[str] = None

    @field_validator("file_size_kb")
    @classmethod
    def validate_file_size(cls, v):
        if v is not None and v > 10240:  # 10MB limit
            raise ValueError("File size must not exceed 10MB (10240 KB)")
        return v

    @field_validator("file_url")
    @classmethod
    def validate_file_url(cls, v):
        if not v.startswith(("http://", "https://", "s3://", "/")):
            raise ValueError("File URL must be a valid URL or path")
        return v

class DocumentCreate(DocumentBase):
    uploaded_by: str = Field(..., min_length=36, max_length=36)

class DocumentUpdate(BaseModel):
    booking_id: Optional[str] = None
    customer_id: Optional[str] = None
    document_type: Optional[DocumentTypeEnum] = None
    file_name: Optional[str] = Field(None, min_length=1, max_length=255)
    file_url: Optional[str] = Field(None, min_length=1, max_length=500)
    file_size_kb: Optional[int] = Field(None, ge=0)
    mime_type: Optional[str] = Field(None, max_length=100)
    description: Optional[str] = None

    @field_validator("file_size_kb")
    @classmethod
    def validate_file_size(cls, v):
        if v is not None and v > 10240:
            raise ValueError("File size must not exceed 10MB (10240 KB)")
        return v

    @field_validator("file_url")
    @classmethod
    def validate_file_url(cls, v):
        if v is not None and not v.startswith(("http://", "https://", "s3://", "/")):
            raise ValueError("File URL must be a valid URL or path")
        return v

class DocumentResponse(DocumentBase):
    id: str
    uploaded_by: str
    created_at: datetime
    updated_at: datetime

    model_config = ConfigDict(from_attributes=True)

class DocumentDetailResponse(DocumentResponse):
    uploader_name: Optional[str] = None
    booking_number: Optional[str] = None
    customer_name: Optional[str] = None

    model_config = ConfigDict(from_attributes=True)