export const formatArrViewlog = (inputArray) => {
  if (!Array.isArray(inputArray) || inputArray.length === 0) {
    return [];
  }

  return Object.keys(inputArray[0]).map((key) => {
    let value = inputArray[0][key];

    if (value !== null && value !== undefined) {
      if (
        Array.isArray(value) &&
        value.length > 0 &&
        value[0].hasOwnProperty("service_name")
      ) {
        value = [value.map((service) => service.service_name).join(", ")];
      }
    } else {
      value = "";
    }

    return { label: key, value };
  });
};

export const extractKeysFromArray = (arr) => {
  const importKeys = [
    "state_name",
    "country_code",
    "services",
    "special_services",
    "loading_or_onloading_date",
    "equipment",
    "size",
    "type",
    "commodity",
    "load_type_code",
    "terminals",
    "pickup_date",
    "origin_destination",
    "delivery_date",
    "scac_code",
    "quantity",
    "weight",
    "weight_type",
    "un_number",
    "class",
    "notes_for_carrier",
    "notes",
    "hazmat",
    "pickup_time_start",
    "pickup_time_end",
    "delivery_time_start",
    "delivery_time_end",
    "destination_zip",
    "destination_city",
    "destination_state_code",
    "destination_port_id",
    "destination_lat",
    "destination_lng",
  ];

  const exportKeys = [
    "state_name",
    "country_code",
    "services",
    "special_services",
    "loading_or_onloading_date",
    "equipment",
    "size",
    "type",
    "commodity",
    "load_type_code",
    "terminals",
    "pickup_date",
    "origin_destination",
    "delivery_date",
    "scac_code",
    "quantity",
    "weight",
    "weight_type",
    "un_number",
    "class",
    "notes_for_carrier",
    "notes",
    "hazmat",
    "pickup_time_start",
    "pickup_time_end",
    "delivery_time_start",
    "delivery_time_end",
    "origin_zip",
    "origin_city",
    "origin_state_code",
    "origin_port_id",
    "origin_lat",
    "origin_lng",
  ];

  const allowedKeys =
    arr[0]?.load_type_code === "import" ? importKeys : exportKeys;

  return arr.map((obj) => {
    const extractedObj = {};
    for (const key of allowedKeys) {
      if (obj.hasOwnProperty(key)) {
        extractedObj[key] = obj[key];
      }
    }
    return extractedObj;
  });
};
