from typing import Annotated, Optional from asyncreq import request from fastapi import APIRouter, Header, HTTPException, Request from src.api.config import API_FLIGHTS from src.api.routes.auth import checkAuth from src.api.schemas.flight import Flight, FlightCreate, FlightUpdate router = APIRouter() @router.get("/{id}", response_model=Flight) async def get_flight_by_id( id: int, req: Request, ): request_id = req.state.request_id header = {"x-api-request-id": request_id} (response, status, _) = await request(f"{API_FLIGHTS}/{id}", "GET", headers=header) if status < 200 or status > 204: raise HTTPException(status_code=status, detail=response) return response @router.post("", response_model=Flight) async def create_flight( flight: FlightCreate, req: Request, authorization: Annotated[str | None, Header()] = None, ): auth = await checkAuth(req, authorization, isAirline=True) flight_data = flight.model_dump() flight_data["user_id"] = auth["id"] request_id = req.state.request_id header = {"x-api-request-id": request_id} (response, status, _) = await request( f"{API_FLIGHTS}", "POST", json=flight_data, headers=header ) if status < 200 or status > 204: raise HTTPException(status_code=status, detail=response) return response @router.patch("/{id}", response_model=Flight) async def update_flight( id: int, flight_update: FlightUpdate, req: Request, authorization: Annotated[str | None, Header()] = None, ): auth = await checkAuth(req, authorization, isAirline=True) update = flight_update.model_dump() update["user_id"] = auth["id"] request_id = req.state.request_id header = {"x-api-request-id": request_id} (response, status, _) = await request( f"{API_FLIGHTS}/{id}", "PATCH", json=update, headers=header ) if status < 200 or status > 204: raise HTTPException(status_code=status, detail=response) return response @router.get("", response_model=list[Flight]) async def get_flights( req: Request, origin: Optional[str] = None, destination: Optional[str] = None, lastUpdated: Optional[str] = None, future: Optional[str] = None, ): query = {} if origin: query["origin"] = origin if destination: query["destination"] = destination if lastUpdated: query["lastUpdated"] = lastUpdated if future: query["future"] = future request_id = req.state.request_id header = {"x-api-request-id": request_id} (response, status, _) = await request( f"{API_FLIGHTS}", "GET", query=query, headers=header ) if status < 200 or status > 204: raise HTTPException(status_code=status, detail=response) return response