// Code generated by protoc-gen-ts-server. DO NOT EDIT.
// source: worldmonitor/aviation/v1/service.proto

export interface ListAirportDelaysRequest {
  pageSize: number;
  cursor: string;
  region: AirportRegion;
  minSeverity: FlightDelaySeverity;
}

export interface ListAirportDelaysResponse {
  alerts: AirportDelayAlert[];
  pagination?: PaginationResponse;
}

export interface AirportDelayAlert {
  id: string;
  iata: string;
  icao: string;
  name: string;
  city: string;
  country: string;
  location?: GeoCoordinates;
  region: AirportRegion;
  delayType: FlightDelayType;
  severity: FlightDelaySeverity;
  avgDelayMinutes: number;
  delayedFlightsPct: number;
  cancelledFlights: number;
  totalFlights: number;
  reason: string;
  source: FlightDelaySource;
  updatedAt: number;
}

export interface GeoCoordinates {
  latitude: number;
  longitude: number;
}

export interface PaginationResponse {
  nextCursor: string;
  totalCount: number;
}

export interface GetAirportOpsSummaryRequest {
  airports: string[];
}

export interface GetAirportOpsSummaryResponse {
  summaries: AirportOpsSummary[];
  cacheHit: boolean;
}

export interface AirportOpsSummary {
  iata: string;
  icao: string;
  name: string;
  timezone: string;
  delayPct: number;
  avgDelayMinutes: number;
  cancellationRate: number;
  totalFlights: number;
  closureStatus: boolean;
  notamFlags: string[];
  severity: FlightDelaySeverity;
  topDelayReasons: string[];
  source: string;
  updatedAt: number;
}

export interface ListAirportFlightsRequest {
  airport: string;
  direction: FlightDirection;
  limit: number;
}

export interface ListAirportFlightsResponse {
  flights: FlightInstance[];
  totalAvailable: number;
  source: string;
  updatedAt: number;
}

export interface FlightInstance {
  flightNumber: string;
  date: string;
  operatingCarrier?: Carrier;
  origin?: AirportRef;
  destination?: AirportRef;
  scheduledDeparture: number;
  estimatedDeparture: number;
  actualDeparture: number;
  scheduledArrival: number;
  estimatedArrival: number;
  actualArrival: number;
  status: FlightInstanceStatus;
  delayMinutes: number;
  cancelled: boolean;
  diverted: boolean;
  gate: string;
  terminal: string;
  aircraftIcao24: string;
  aircraftType: string;
  codeshareFlightNumbers: string[];
  source: string;
  updatedAt: number;
}

export interface Carrier {
  iataCode: string;
  icaoCode: string;
  name: string;
}

export interface AirportRef {
  iata: string;
  icao: string;
  name: string;
  timezone: string;
}

export interface GetCarrierOpsRequest {
  airports: string[];
  minFlights: number;
}

export interface GetCarrierOpsResponse {
  carriers: CarrierOpsSummary[];
  source: string;
  updatedAt: number;
}

export interface CarrierOpsSummary {
  carrier?: Carrier;
  airport: string;
  totalFlights: number;
  delayedCount: number;
  cancelledCount: number;
  avgDelayMinutes: number;
  delayPct: number;
  cancellationRate: number;
  updatedAt: number;
}

export interface GetFlightStatusRequest {
  flightNumber: string;
  date: string;
  origin: string;
}

export interface GetFlightStatusResponse {
  flights: FlightInstance[];
  source: string;
  cacheHit: boolean;
}

export interface TrackAircraftRequest {
  icao24: string;
  callsign: string;
  swLat: number;
  swLon: number;
  neLat: number;
  neLon: number;
}

export interface TrackAircraftResponse {
  positions: PositionSample[];
  source: string;
  updatedAt: number;
}

export interface PositionSample {
  icao24: string;
  callsign: string;
  lat: number;
  lon: number;
  altitudeM: number;
  groundSpeedKts: number;
  trackDeg: number;
  verticalRate: number;
  onGround: boolean;
  source: PositionSource;
  observedAt: number;
}

export interface GetYoutubeLiveStreamInfoRequest {
  channel: string;
  videoId: string;
}

export interface GetYoutubeLiveStreamInfoResponse {
  videoId: string;
  isLive: boolean;
  channelExists: boolean;
  channelName: string;
  hlsUrl: string;
  title: string;
  error: string;
}

export interface SearchFlightPricesRequest {
  origin: string;
  destination: string;
  departureDate: string;
  returnDate: string;
  adults: number;
  cabin: CabinClass;
  nonstopOnly: boolean;
  maxResults: number;
  currency: string;
  market: string;
}

export interface SearchFlightPricesResponse {
  quotes: PriceQuote[];
  provider: string;
  isDemoMode: boolean;
  updatedAt: number;
  isIndicative: boolean;
  degraded: boolean;
  error: string;
}

export interface PriceQuote {
  id: string;
  origin: string;
  destination: string;
  departureDate: string;
  returnDate: string;
  carrier?: Carrier;
  priceAmount: number;
  currency: string;
  cabin: CabinClass;
  stops: number;
  durationMinutes: number;
  bookingUrl: string;
  provider: string;
  isIndicative: boolean;
  observedAt: number;
  checkoutRef: string;
  expiresAt: number;
}

export interface ListAviationNewsRequest {
  entities: string[];
  windowHours: number;
  maxItems: number;
}

export interface ListAviationNewsResponse {
  items: AviationNewsItem[];
  source: string;
  updatedAt: number;
}

export interface AviationNewsItem {
  id: string;
  title: string;
  url: string;
  sourceName: string;
  publishedAt: number;
  snippet: string;
  matchedEntities: string[];
  imageUrl: string;
}

export interface SearchGoogleFlightsRequest {
  origin: string;
  destination: string;
  departureDate: string;
  returnDate: string;
  cabinClass: string;
  maxStops: string;
  departureWindow: string;
  airlines: string[];
  sortBy: string;
  passengers: number;
}

export interface SearchGoogleFlightsResponse {
  flights: GoogleFlightResult[];
  degraded: boolean;
  error: string;
}

export interface GoogleFlightResult {
  legs: GoogleFlightLeg[];
  price: number;
  durationMinutes: number;
  stops: number;
}

export interface GoogleFlightLeg {
  airlineCode: string;
  flightNumber: string;
  departureAirport: string;
  arrivalAirport: string;
  departureDatetime: string;
  arrivalDatetime: string;
  durationMinutes: number;
}

export interface SearchGoogleDatesRequest {
  origin: string;
  destination: string;
  startDate: string;
  endDate: string;
  tripDuration: number;
  isRoundTrip: boolean;
  cabinClass: string;
  maxStops: string;
  departureWindow: string;
  airlines: string[];
  sortByPrice: boolean;
  passengers: number;
}

export interface SearchGoogleDatesResponse {
  dates: DatePriceEntry[];
  degraded: boolean;
  error: string;
}

export interface DatePriceEntry {
  date: string;
  returnDate: string;
  price: number;
}

export type AirportRegion = "AIRPORT_REGION_UNSPECIFIED" | "AIRPORT_REGION_AMERICAS" | "AIRPORT_REGION_EUROPE" | "AIRPORT_REGION_APAC" | "AIRPORT_REGION_MENA" | "AIRPORT_REGION_AFRICA";

export type CabinClass = "CABIN_CLASS_UNSPECIFIED" | "CABIN_CLASS_ECONOMY" | "CABIN_CLASS_PREMIUM_ECONOMY" | "CABIN_CLASS_BUSINESS" | "CABIN_CLASS_FIRST";

export type FlightDelaySeverity = "FLIGHT_DELAY_SEVERITY_UNSPECIFIED" | "FLIGHT_DELAY_SEVERITY_NORMAL" | "FLIGHT_DELAY_SEVERITY_MINOR" | "FLIGHT_DELAY_SEVERITY_MODERATE" | "FLIGHT_DELAY_SEVERITY_MAJOR" | "FLIGHT_DELAY_SEVERITY_SEVERE" | "FLIGHT_DELAY_SEVERITY_UNKNOWN";

export type FlightDelaySource = "FLIGHT_DELAY_SOURCE_UNSPECIFIED" | "FLIGHT_DELAY_SOURCE_FAA" | "FLIGHT_DELAY_SOURCE_EUROCONTROL" | "FLIGHT_DELAY_SOURCE_COMPUTED" | "FLIGHT_DELAY_SOURCE_AVIATIONSTACK" | "FLIGHT_DELAY_SOURCE_NOTAM";

export type FlightDelayType = "FLIGHT_DELAY_TYPE_UNSPECIFIED" | "FLIGHT_DELAY_TYPE_GROUND_STOP" | "FLIGHT_DELAY_TYPE_GROUND_DELAY" | "FLIGHT_DELAY_TYPE_DEPARTURE_DELAY" | "FLIGHT_DELAY_TYPE_ARRIVAL_DELAY" | "FLIGHT_DELAY_TYPE_GENERAL" | "FLIGHT_DELAY_TYPE_CLOSURE";

export type FlightDirection = "FLIGHT_DIRECTION_UNSPECIFIED" | "FLIGHT_DIRECTION_DEPARTURE" | "FLIGHT_DIRECTION_ARRIVAL" | "FLIGHT_DIRECTION_BOTH";

export type FlightInstanceStatus = "FLIGHT_INSTANCE_STATUS_UNSPECIFIED" | "FLIGHT_INSTANCE_STATUS_SCHEDULED" | "FLIGHT_INSTANCE_STATUS_BOARDING" | "FLIGHT_INSTANCE_STATUS_DEPARTED" | "FLIGHT_INSTANCE_STATUS_AIRBORNE" | "FLIGHT_INSTANCE_STATUS_LANDED" | "FLIGHT_INSTANCE_STATUS_ARRIVED" | "FLIGHT_INSTANCE_STATUS_CANCELLED" | "FLIGHT_INSTANCE_STATUS_DIVERTED" | "FLIGHT_INSTANCE_STATUS_UNKNOWN";

export type PositionSource = "POSITION_SOURCE_UNSPECIFIED" | "POSITION_SOURCE_OPENSKY" | "POSITION_SOURCE_WINGBITS" | "POSITION_SOURCE_SIMULATED";

export interface FieldViolation {
  field: string;
  description: string;
}

export class ValidationError extends Error {
  violations: FieldViolation[];

  constructor(violations: FieldViolation[]) {
    super("Validation failed");
    this.name = "ValidationError";
    this.violations = violations;
  }
}

export class ApiError extends Error {
  statusCode: number;
  body: string;

  constructor(statusCode: number, message: string, body: string) {
    super(message);
    this.name = "ApiError";
    this.statusCode = statusCode;
    this.body = body;
  }
}

export interface ServerContext {
  request: Request;
  pathParams: Record<string, string>;
  headers: Record<string, string>;
}

export interface ServerOptions {
  onError?: (error: unknown, req: Request) => Response | Promise<Response>;
  validateRequest?: (methodName: string, body: unknown) => FieldViolation[] | undefined;
}

export interface RouteDescriptor {
  method: string;
  path: string;
  handler: (req: Request) => Promise<Response>;
}

export interface AviationServiceHandler {
  listAirportDelays(ctx: ServerContext, req: ListAirportDelaysRequest): Promise<ListAirportDelaysResponse>;
  getAirportOpsSummary(ctx: ServerContext, req: GetAirportOpsSummaryRequest): Promise<GetAirportOpsSummaryResponse>;
  listAirportFlights(ctx: ServerContext, req: ListAirportFlightsRequest): Promise<ListAirportFlightsResponse>;
  getCarrierOps(ctx: ServerContext, req: GetCarrierOpsRequest): Promise<GetCarrierOpsResponse>;
  getFlightStatus(ctx: ServerContext, req: GetFlightStatusRequest): Promise<GetFlightStatusResponse>;
  trackAircraft(ctx: ServerContext, req: TrackAircraftRequest): Promise<TrackAircraftResponse>;
  getYoutubeLiveStreamInfo(ctx: ServerContext, req: GetYoutubeLiveStreamInfoRequest): Promise<GetYoutubeLiveStreamInfoResponse>;
  searchFlightPrices(ctx: ServerContext, req: SearchFlightPricesRequest): Promise<SearchFlightPricesResponse>;
  listAviationNews(ctx: ServerContext, req: ListAviationNewsRequest): Promise<ListAviationNewsResponse>;
  searchGoogleFlights(ctx: ServerContext, req: SearchGoogleFlightsRequest): Promise<SearchGoogleFlightsResponse>;
  searchGoogleDates(ctx: ServerContext, req: SearchGoogleDatesRequest): Promise<SearchGoogleDatesResponse>;
}

export function createAviationServiceRoutes(
  handler: AviationServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/aviation/v1/list-airport-delays",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: ListAirportDelaysRequest = {
            pageSize: Number(params.get("page_size") ?? "0"),
            cursor: params.get("cursor") ?? "",
            region: (params.get("region") ?? "AIRPORT_REGION_UNSPECIFIED") as AirportRegion,
            minSeverity: (params.get("min_severity") ?? "FLIGHT_DELAY_SEVERITY_UNSPECIFIED") as FlightDelaySeverity,
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listAirportDelays", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.listAirportDelays(ctx, body);
          return new Response(JSON.stringify(result as ListAirportDelaysResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/get-airport-ops-summary",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: GetAirportOpsSummaryRequest = {
            airports: params.getAll("airports"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getAirportOpsSummary", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getAirportOpsSummary(ctx, body);
          return new Response(JSON.stringify(result as GetAirportOpsSummaryResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/list-airport-flights",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: ListAirportFlightsRequest = {
            airport: params.get("airport") ?? "",
            direction: (params.get("direction") ?? "FLIGHT_DIRECTION_UNSPECIFIED") as FlightDirection,
            limit: Number(params.get("limit") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listAirportFlights", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.listAirportFlights(ctx, body);
          return new Response(JSON.stringify(result as ListAirportFlightsResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/get-carrier-ops",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: GetCarrierOpsRequest = {
            airports: params.getAll("airports"),
            minFlights: Number(params.get("min_flights") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getCarrierOps", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getCarrierOps(ctx, body);
          return new Response(JSON.stringify(result as GetCarrierOpsResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/get-flight-status",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: GetFlightStatusRequest = {
            flightNumber: params.get("flight_number") ?? "",
            date: params.get("date") ?? "",
            origin: params.get("origin") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getFlightStatus", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getFlightStatus(ctx, body);
          return new Response(JSON.stringify(result as GetFlightStatusResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/track-aircraft",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: TrackAircraftRequest = {
            icao24: params.get("icao24") ?? "",
            callsign: params.get("callsign") ?? "",
            swLat: Number(params.get("sw_lat") ?? "0"),
            swLon: Number(params.get("sw_lon") ?? "0"),
            neLat: Number(params.get("ne_lat") ?? "0"),
            neLon: Number(params.get("ne_lon") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("trackAircraft", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.trackAircraft(ctx, body);
          return new Response(JSON.stringify(result as TrackAircraftResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/get-youtube-live-stream-info",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: GetYoutubeLiveStreamInfoRequest = {
            channel: params.get("channel") ?? "",
            videoId: params.get("video_id") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getYoutubeLiveStreamInfo", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getYoutubeLiveStreamInfo(ctx, body);
          return new Response(JSON.stringify(result as GetYoutubeLiveStreamInfoResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/search-flight-prices",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: SearchFlightPricesRequest = {
            origin: params.get("origin") ?? "",
            destination: params.get("destination") ?? "",
            departureDate: params.get("departure_date") ?? "",
            returnDate: params.get("return_date") ?? "",
            adults: Number(params.get("adults") ?? "0"),
            cabin: (params.get("cabin") ?? "CABIN_CLASS_UNSPECIFIED") as CabinClass,
            nonstopOnly: params.get("nonstop_only") === "true",
            maxResults: Number(params.get("max_results") ?? "0"),
            currency: params.get("currency") ?? "",
            market: params.get("market") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("searchFlightPrices", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.searchFlightPrices(ctx, body);
          return new Response(JSON.stringify(result as SearchFlightPricesResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/list-aviation-news",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: ListAviationNewsRequest = {
            entities: params.getAll("entities"),
            windowHours: Number(params.get("window_hours") ?? "0"),
            maxItems: Number(params.get("max_items") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("listAviationNews", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.listAviationNews(ctx, body);
          return new Response(JSON.stringify(result as ListAviationNewsResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/search-google-flights",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: SearchGoogleFlightsRequest = {
            origin: params.get("origin") ?? "",
            destination: params.get("destination") ?? "",
            departureDate: params.get("departure_date") ?? "",
            returnDate: params.get("return_date") ?? "",
            cabinClass: params.get("cabin_class") ?? "",
            maxStops: params.get("max_stops") ?? "",
            departureWindow: params.get("departure_window") ?? "",
            airlines: params.getAll("airlines"),
            sortBy: params.get("sort_by") ?? "",
            passengers: Number(params.get("passengers") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("searchGoogleFlights", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.searchGoogleFlights(ctx, body);
          return new Response(JSON.stringify(result as SearchGoogleFlightsResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/aviation/v1/search-google-dates",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: SearchGoogleDatesRequest = {
            origin: params.get("origin") ?? "",
            destination: params.get("destination") ?? "",
            startDate: params.get("start_date") ?? "",
            endDate: params.get("end_date") ?? "",
            tripDuration: Number(params.get("trip_duration") ?? "0"),
            isRoundTrip: params.get("is_round_trip") === "true",
            cabinClass: params.get("cabin_class") ?? "",
            maxStops: params.get("max_stops") ?? "",
            departureWindow: params.get("departure_window") ?? "",
            airlines: params.getAll("airlines"),
            sortByPrice: params.get("sort_by_price") === "true",
            passengers: Number(params.get("passengers") ?? "0"),
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("searchGoogleDates", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.searchGoogleDates(ctx, body);
          return new Response(JSON.stringify(result as SearchGoogleDatesResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
  ];
}

