from pydantic import BaseModel, validator
from datetime import datetime
from typing import Optional
from enum import Enum


class DepartureStatus(str, Enum):
    BOOKED_OUT = "BOOKED_OUT"
    DEPARTED = "DEPARTED"
    CANCELLED = "CANCELLED"


class SubmissionSource(str, Enum):
    ADMIN = "ADMIN"
    PUBLIC = "PUBLIC"


class DepartureBase(BaseModel):
    registration: str
    type: Optional[str] = None
    callsign: Optional[str] = None
    pob: int
    out_to: str
    etd: Optional[datetime] = None  # Estimated Time of Departure
    notes: Optional[str] = None

    @validator('registration')
    def validate_registration(cls, v):
        if not v or len(v.strip()) == 0:
            raise ValueError('Aircraft registration is required')
        return v.strip().upper()

    @validator('out_to')
    def validate_out_to(cls, v):
        if not v or len(v.strip()) == 0:
            raise ValueError('Destination airport is required')
        return v.strip()

    @validator('pob')
    def validate_pob(cls, v):
        if v is not None and v < 1:
            raise ValueError('Persons on board must be at least 1')
        return v


class DepartureCreate(DepartureBase):
    pass


class DepartureUpdate(BaseModel):
    registration: Optional[str] = None
    type: Optional[str] = None
    callsign: Optional[str] = None
    pob: Optional[int] = None
    out_to: Optional[str] = None
    etd: Optional[datetime] = None
    notes: Optional[str] = None


class DepartureStatusUpdate(BaseModel):
    status: DepartureStatus
    timestamp: Optional[datetime] = None


class Departure(DepartureBase):
    id: int
    status: DepartureStatus
    created_dt: datetime
    etd: Optional[datetime] = None
    departed_dt: Optional[datetime] = None
    updated_at: datetime
    submitted_via: Optional[SubmissionSource] = None
    pilot_email: Optional[str] = None

    class Config:
        from_attributes = True
