/**
 * Convert the mixed `IFlight[]` schedule-search response into a flat
 * `ISimpleFlight[]` for rendering.
 *
 * Connecting flights are folded into a synthetic MultiLeg shape so the
 * existing FlightCard can render them with combined leg numbers, both
 * airline logos, and the total flying time — matching Angular's
 * `schedule-list-flight-header` for connecting flights.
 *
 * @module
 */

import type { FlightStatus, IFlightLeg } from "@/features/online-board/types.js";
import type { ISimpleFlight } from "./types.js";

export function extractSimpleFlights(
  flights: Array<{ routeType: string }>,
): ISimpleFlight[] {
  const out: ISimpleFlight[] = [];
  for (const f of flights) {
    if (f.routeType === "Direct" || f.routeType === "MultiLeg") {
      out.push(f as unknown as ISimpleFlight);
      continue;
    }
    if (f.routeType === "Connecting") {
      const conn = f as unknown as {
        flights: ISimpleFlight[];
        flyingTime: string;
        status: FlightStatus;
      };
      const first = conn.flights[0];
      if (!first) continue;
      const allLegs: IFlightLeg[] = [];
      for (const child of conn.flights) {
        if (child.routeType === "Direct") allLegs.push(child.leg);
        else allLegs.push(...child.legs);
      }
      const synthetic = {
        routeType: "MultiLeg",
        flightId: first.flightId,
        flyingTime: conn.flyingTime,
        operatingBy: first.operatingBy,
        id: conn.flights.map((c) => c.id).join("+"),
        status: conn.status,
        legs: allLegs,
        // Carry through the original child flight numbers so the header
        // can display 'SU 6188, SU 6233'.
        _childFlightIds: conn.flights.map((c) => c.flightId),
      } as unknown as ISimpleFlight;
      out.push(synthetic);
    }
  }
  return out;
}
