/**
 * Movement Dashboard: show a flight number on its airport transfer even
 * when ops never picked "Linked transport" on the flight (client
 * feedback 2026-10-17 — most flights are left unlinked).
 *
 * - Arrival → the airport row on the arrival date, else the earliest.
 * - Departure → the row on the departure date or the day before (a
 *   02:50 flight is picked up the evening before), else the latest.
 * - No direction → only a row on the flight's date, or the single
 *   row when the booking has one row and one flight.
 * Rows already linked to a flight are never reused.
 */
export interface MatchableFlight {
  direction?: string | null;
  arrival_time?: string | null;
  departure_time?: string | null;
}

export interface AirportRow {
  id: string;
  date: unknown;
}

const dayOf = (v: unknown): string | null => {
  if (v instanceof Date && !Number.isNaN(v.getTime())) {
    const m = String(v.getMonth() + 1).padStart(2, '0');
    const d = String(v.getDate()).padStart(2, '0');
    return `${v.getFullYear()}-${m}-${d}`;
  }
  const match = /^(\d{4}-\d{2}-\d{2})/.exec(String(v ?? ''));
  return match ? match[1] : null;
};

const prevDay = (day: string): string => {
  const d = new Date(`${day}T00:00:00Z`);
  d.setUTCDate(d.getUTCDate() - 1);
  return d.toISOString().slice(0, 10);
};

/** Returns transport row id → matched flight. */
export function matchUnlinkedFlights<F extends MatchableFlight>(
  rows: ReadonlyArray<AirportRow>,
  flights: ReadonlyArray<F>,
  linkedRowIds: ReadonlySet<string>,
): Map<string, F> {
  const out = new Map<string, F>();
  const free = rows
    .filter((r) => !linkedRowIds.has(r.id))
    .sort((a, b) => String(dayOf(a.date)).localeCompare(String(dayOf(b.date))));
  const take = (day: string | null) => {
    if (!day) return undefined;
    const i = free.findIndex((r) => dayOf(r.date) === day);
    return i >= 0 ? free.splice(i, 1)[0] : undefined;
  };
  const dir = (f: F) => String(f.direction || '').toLowerCase();
  const singleRowSingleFlight = free.length === 1 && flights.length === 1;

  for (const f of flights.filter((x) => dir(x) === 'arrival')) {
    const day = dayOf(f.arrival_time) ?? dayOf(f.departure_time);
    const row = take(day) ?? free.shift();
    if (row) out.set(row.id, f);
  }
  for (const f of flights.filter((x) => dir(x) === 'departure')) {
    const day = dayOf(f.departure_time) ?? dayOf(f.arrival_time);
    const row = take(day) ?? (day ? take(prevDay(day)) : undefined) ?? free.pop();
    if (row) out.set(row.id, f);
  }
  for (const f of flights.filter((x) => dir(x) !== 'arrival' && dir(x) !== 'departure')) {
    const row =
      take(dayOf(f.arrival_time) ?? dayOf(f.departure_time)) ??
      (singleRowSingleFlight ? free.shift() : undefined);
    if (row) out.set(row.id, f);
  }
  return out;
}
