import { parseISO, subHours, isAfter, isSameDay } from "date-fns";
import type { ISimpleFlight } from "../../../types.js";

/**
 * Flight Status button is visible when:
 * - the operating carrier is in airlinesWithStatus
 * - departure is same-day as now
 * - now is within `availableFromHours` before departure
 */
export function canViewFlightStatus(
  flight: ISimpleFlight,
  now: Date,
  availableFromHours: number,
  airlinesWithStatus: Set<string>,
): boolean {
  const carrier = flight.operatingBy.carrier;
  if (!carrier || !airlinesWithStatus.has(carrier)) return false;

  const leg = flight.routeType === "Direct" ? flight.leg : flight.legs[0];
  if (!leg) return false;

  const depUtc = leg.departure.times.scheduledDeparture.utc;
  if (!depUtc) return false;

  const departure = parseISO(depUtc);
  if (isNaN(departure.getTime())) return false;

  if (!isSameDay(now, departure)) return false;

  const availableFrom = subHours(departure, availableFromHours);
  return isAfter(now, availableFrom);
}
