import type { IOption } from "@/types";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";

let cachedLanguageOptions: IOption[] | null = null;
let pendingLanguageOptionsRequest: Promise<IOption[]> | null = null;

export const fetchLanguageOptions = async (): Promise<IOption[]> => {
  if (cachedLanguageOptions) {
    return cachedLanguageOptions;
  }

  if (pendingLanguageOptionsRequest) {
    return pendingLanguageOptionsRequest;
  }

  pendingLanguageOptionsRequest = API_Instance.get(API_Constants.languages)
    .then((res) => {
      const rawLanguages = Array.isArray(res?.data?.data) ? res.data.data : [];
      const options = rawLanguages.map((item: any) => {
        if (typeof item === "string") {
          return { label: item, value: item };
        }

        return {
          label: item?.label ?? item?.value ?? "",
          value: item?.value ?? item?.label ?? "",
        };
      });

      cachedLanguageOptions = options;
      return options;
    })
    .catch((error) => {
      pendingLanguageOptionsRequest = null;
      throw error;
    });

  return pendingLanguageOptionsRequest;
};