const DELAY_THRESHOLD_MINUTES = 15;

function minutesDiff(later, earlier) {
  if (!later || !earlier) return 0;
  return Math.round((new Date(later) - new Date(earlier)) / 60000);
}

function isCancelled(detailAttrs = {}) {
  return (
    detailAttrs.FlightStatus === "CANCELLED" ||
    detailAttrs.Status === "CANCELLED" ||
    detailAttrs.Cancelled === "true"
  );
}

module.exports = function deriveFlightStatus(detailAttrs = {}) {
  const scheduledDep = detailAttrs.ScheduledDepartureTime;
  const estimatedDep = detailAttrs.EstimatedDepartureTime;
  const actualDep = detailAttrs.ActualDepartureTime;

  const scheduledArr = detailAttrs.ScheduledArrivalTime;
  const actualArr = detailAttrs.ActualArrivalTime;

  // 1️⃣ Cancellation check (highest priority)
  if (isCancelled(detailAttrs)) {
    return {
      status: "CANCELLED",
      delayMinutes: null,
      basis: "CARRIER_STATUS",
    };
  }

  // 2️⃣ Arrived
  if (actualArr && scheduledArr) {
    return {
      status: "ARRIVED",
      delayMinutes: minutesDiff(actualArr, scheduledArr),
      basis: "ACTUAL_ARRIVAL",
    };
  }

  // 3️⃣ Departed
  if (actualDep && scheduledDep) {
    return {
      status: "DEPARTED",
      delayMinutes: minutesDiff(actualDep, scheduledDep),
      basis: "ACTUAL_DEPARTURE",
    };
  }

  // 4️⃣ Estimated departure → delay / on-time
  if (estimatedDep && scheduledDep) {
    const delayMinutes = minutesDiff(estimatedDep, scheduledDep);

    return {
      status:
        delayMinutes >= DELAY_THRESHOLD_MINUTES ? "DELAYED" : "ON_TIME",
      delayMinutes,
      basis: "ESTIMATED_DEPARTURE",
    };
  }

  // 5️⃣ Scheduled only
  if (scheduledDep) {
    return {
      status: "SCHEDULED",
      delayMinutes: 0,
      basis: "SCHEDULED_ONLY",
    };
  }

  // 6️⃣ Fallback
  return {
    status: "UNKNOWN",
    delayMinutes: null,
    basis: "INSUFFICIENT_DATA",
  };
};
