const getSimBriefFlightPlan = async (simBriefUsername: string) => {
  const flightPlanURL = `https://www.simbrief.com/api/xml.fetcher.php?username=${simBriefUsername}&json=1`;
  let response: Response;
  let success = false;
  try {
    response = await fetch(flightPlanURL);
    success = true;
    //eslint-disable-next-line @typescript-eslint/no-explicit-any
  } catch (e: any) {
    response = e.response;
  }
  return {
    success,
    data: await response.json(),
  };
};

export const ImportFlightPlan = async (
  username: string,
  maxZFW: number,
  maxTOW: number,
  maxFuel: number,
  isImperial: boolean
) => {
  const flightPlan = await getSimBriefFlightPlan(username);
  if (!flightPlan.success) {
    return {
      type: 'error',
      message: flightPlan.data.status,
    };
  }

  const data = flightPlan.data;

  if (!['MD11', 'MD1F'].includes(data.aircraft.icao_code)) {
    return {
      type: 'error',
      message: `Your SimBrief plan is not for a MD-11`,
    };
  }

  let convFactor = 1;
  if (data.params.units === 'kgs' && isImperial) convFactor = 2.20462262185;
  if (data.params.units === 'lbs' && !isImperial) convFactor = 1 / 2.20462262185;

  return {
    type: 'data',
    message: {
      plannedZFW: Math.min(maxZFW, Math.round(data.weights.est_zfw * convFactor)),
      plannedGW: Math.min(maxTOW, Math.round(data.weights.est_ramp * convFactor)),
      pax: data.weights.pax_count_actual,
      cargo: Math.round(data.weights.freight_added * convFactor),
      fuel: Math.min(maxFuel, Math.round(data.fuel.plan_ramp * convFactor)),
    },
  };
};
