/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable spellcheck/spell-checker */
import { useEffect, useState } from 'react';
import { getAllConfigurations } from '@/app/launches/service';

export interface ConfigurationOption { value: string, label: string }

// One request per page load, shared by every configuration dropdown.
let cache: ConfigurationOption[] | null = null;
let inflight: Promise<ConfigurationOption[]> | null = null;

const loadConfigurations = (): Promise<ConfigurationOption[]> => {
  if (cache) return Promise.resolve(cache);
  if (!inflight) {
    inflight = getAllConfigurations()
      .then((res: any) => {
        cache = (res?.data || []).map((c: { configuration_name: string }) => ({
          value: c.configuration_name,
          label: c.configuration_name,
        }));
        return cache as ConfigurationOption[];
      })
      .finally(() => {
 inflight = null;
});
  }
  return inflight;
};

// Configurations no longer depend on the selected project: the dropdown always lists all of them.
export function useAllConfigurations() {
  const [options, setOptions] = useState<ConfigurationOption[]>(cache || []);

  useEffect(() => {
    if (cache) {
 setOptions(cache); return;
}
    let cancelled = false;
    loadConfigurations()
      .then((list) => {
 if (!cancelled) setOptions(list);
})
      .catch(() => {
 if (!cancelled) setOptions([]);
});
    return () => {
 cancelled = true;
};
  }, []);

  return options;
}
