from typing import Optional from asyncreq import request from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException from sqlalchemy.orm import Session from src.api.config import API_MESSAGES from src.api.cruds import flight as flight_crud from src.api.db import get_db from src.api.schemas.flight import Flight, FlightCreate, FlightStatusUpdate router = APIRouter() @router.get("/{id}", response_model=Flight) def get_flight_by_id(id: int, db: Session = Depends(get_db)): db_flight = flight_crud.get_flight_by_id(db, id) if db_flight is None: raise HTTPException(status_code=404, detail="Flight not found") return db_flight @router.post("", response_model=Flight) def create_flight(flight: FlightCreate, db: Session = Depends(get_db)): return flight_crud.create_flight(db=db, flight=flight) @router.patch("/{id}", response_model=Flight) async def update_flight( id: int, status: FlightStatusUpdate, background_tasks: BackgroundTasks, db: Session = Depends(get_db), ): try: db_flight = flight_crud.update_flight_status(db=db, id=id, status=status) except PermissionError: raise HTTPException(status_code=401, detail="Unauthorized") except KeyError: raise HTTPException(status_code=404, detail="Flight not found") msg = status.model_dump() msg["id"] = id msg["flight_code"] = db_flight.flight_code msg["origin"] = db_flight.origin msg["destination"] = db_flight.destination background_tasks.add_task(request, API_MESSAGES, "POST", json=msg) return db_flight @router.get("", response_model=list[Flight]) def get_flights( origin: Optional[str] = None, destination: Optional[str] = None, lastUpdated: Optional[str] = None, db: Session = Depends(get_db), ): if origin and lastUpdated: flights = flight_crud.get_flights_update_origin(db, origin, lastUpdated) elif destination and lastUpdated: flights = flight_crud.get_flights_update_destination( db, destination, lastUpdated ) elif origin: flights = flight_crud.get_flights_by_origin(db=db, origin=origin) elif destination: flights = flight_crud.get_flights_by_destination(db=db, destination=destination) else: flights = flight_crud.get_flights(db=db) if not flights: raise HTTPException(status_code=404, detail="Flights not found") return flights