from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session
from typing import Optional, List
from datetime import datetime
from utils.utils import get_db
from . import handler
from .schema import (
    AircraftCreate, AircraftUpdate, AircraftResponse, AircraftDetailResponse,
    SeatCreate, SeatUpdate, SeatResponse, AircraftStatus, SeatClassType
)

router = APIRouter(prefix="/aircraft", tags=["Aircraft Management"])


@router.post(
    "/",
    response_model=AircraftResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Create Aircraft",
    description="Creates a new aircraft record with registration number, model, manufacturer, and seating capacity. Returns 409 if the registration number already exists. Validates that total_seats is greater than 0 and year_manufactured is greater than 1900."
)
def create_aircraft_route(data: AircraftCreate, db: Session = Depends(get_db)):
    return handler.create_aircraft(db, data)


@router.get(
    "/",
    response_model=List[AircraftResponse],
    summary="List Aircraft",
    description="Returns a paginated list of aircraft. Supports optional filtering by status and search term (matches registration number, model, or manufacturer). Results are ordered by creation date descending."
)
def list_aircraft_route(
    limit: int = Query(20, ge=1, le=100),
    offset: int = Query(0, ge=0),
    status: Optional[AircraftStatus] = Query(None),
    search: Optional[str] = None,
    db: Session = Depends(get_db)
):
    return handler.list_aircraft(db, limit, offset, status.value if status else None, search)


@router.get(
    "/{id}",
    response_model=AircraftResponse,
    summary="Get Aircraft By ID",
    description="Returns a single aircraft record by its unique identifier. Returns 404 if the aircraft does not exist."
)
def get_aircraft_route(id: str, db: Session = Depends(get_db)):
    return handler.get_aircraft(db, id)


@router.put(
    "/{id}",
    response_model=AircraftResponse,
    summary="Update Aircraft",
    description="Updates an existing aircraft record. Only provided fields are updated. Returns 404 if the aircraft does not exist. Returns 409 if the new registration number conflicts with another aircraft."
)
def update_aircraft_route(id: str, data: AircraftUpdate, db: Session = Depends(get_db)):
    return handler.update_aircraft(db, id, data)


@router.delete(
    "/{id}",
    status_code=status.HTTP_200_OK,
    summary="Delete Aircraft",
    description="Deletes an aircraft record. Returns 404 if the aircraft does not exist. Returns 400 if the aircraft has future flight assignments, as aircraft cannot be deleted when they have scheduled flights."
)
def delete_aircraft_route(id: str, db: Session = Depends(get_db)):
    return handler.delete_aircraft(db, id)


@router.get(
    "/{id}/details",
    response_model=AircraftDetailResponse,
    summary="Get Aircraft Details",
    description="Returns detailed aircraft information including all seats configured on the aircraft and all associated flights. Uses eager loading to prevent N+1 queries. Returns 404 if the aircraft does not exist."
)
def get_aircraft_details_route(id: str, db: Session = Depends(get_db)):
    return handler.get_aircraft_details(db, id)


@router.get(
    "/{id}/availability",
    summary="Check Aircraft Availability",
    description="Checks if an aircraft is available for a given date range. Returns availability status, reason, and any conflicting flight assignments. Considers aircraft operational status and existing flight schedules including required turnaround time."
)
def check_aircraft_availability_route(
    id: str,
    start_date: datetime = Query(...),
    end_date: datetime = Query(...),
    db: Session = Depends(get_db)
):
    return handler.check_aircraft_availability(db, id, start_date, end_date)


@router.post(
    "/seats",
    response_model=SeatResponse,
    status_code=status.HTTP_201_CREATED,
    summary="Create Seat",
    description="Creates a new seat configuration for an aircraft. Returns 404 if the aircraft does not exist. Returns 409 if a seat with the same seat number already exists on the specified aircraft."
)
def create_seat_route(data: SeatCreate, db: Session = Depends(get_db)):
    return handler.create_seat(db, data)


@router.get(
    "/seats",
    response_model=List[SeatResponse],
    summary="List Seats",
    description="Returns a paginated list of seats. Supports optional filtering by aircraft_id and class_type. Results are ordered by seat number."
)
def list_seats_route(
    limit: int = Query(20, ge=1, le=100),
    offset: int = Query(0, ge=0),
    aircraft_id: Optional[str] = None,
    class_type: Optional[SeatClassType] = Query(None),
    db: Session = Depends(get_db)
):
    return handler.list_seats(db, limit, offset, aircraft_id, class_type.value if class_type else None)


@router.get(
    "/seats/{id}",
    response_model=SeatResponse,
    summary="Get Seat By ID",
    description="Returns a single seat record by its unique identifier. Returns 404 if the seat does not exist."
)
def get_seat_route(id: str, db: Session = Depends(get_db)):
    return handler.get_seat(db, id)


@router.put(
    "/seats/{id}",
    response_model=SeatResponse,
    summary="Update Seat",
    description="Updates an existing seat record. Only provided fields are updated. Returns 404 if the seat or referenced aircraft does not exist. Returns 409 if the updated seat number conflicts with another seat on the same aircraft."
)
def update_seat_route(id: str, data: SeatUpdate, db: Session = Depends(get_db)):
    return handler.update_seat(db, id, data)


@router.delete(
    "/seats/{id}",
    status_code=status.HTTP_200_OK,
    summary="Delete Seat",
    description="Deletes a seat record. Returns 404 if the seat does not exist."
)
def delete_seat_route(id: str, db: Session = Depends(get_db)):
    return handler.delete_seat(db, id)