export default function useLocation() {
  function getCountries() {
    return useNuxtApp()
      .$api<Record<string, any>>("/json/country.json", {
        method: "GET",
      })
      .then((countries) =>
        countries
          .map((c: any) => c.name)
          .sort((a: string, b: string) => a.localeCompare(b)),
      );
  }

  function getAddressByPostalCode(postalCode: string, country?: string) {
    const countryISOMap: Record<string, string> = {
      Singapore: "sg",
      Malaysia: "my",
      "United States": "us",
      "United Kingdom": "gb",
    };

    const isoCode = country
      ? countryISOMap[country] || country.toLowerCase()
      : undefined;

    return useNuxtApp()
      .$api<Record<string, any>[]>(
        "https://nominatim.openstreetmap.org/search",
        {
          method: "GET",
          query: {
            postalcode: postalCode,
            country: isoCode,
            format: "json",
            limit: 1,
            addressdetails: 1,
          },
          headers: {
            "User-Agent": "iService365-Hygiene-App",
          },
        },
      )
      .then((data) => (data?.length ? data[0] : null));
  }

  function searchLocationByAddress({
    postalCode,
    city,
    address,
    country,
  }: TLocationSearchParams) {
    const searchParts = [postalCode, city, address, country].filter(Boolean);

    return useNuxtApp()
      .$api<Record<string, any>[]>(
        "https://nominatim.openstreetmap.org/search",
        {
          method: "GET",
          query: {
            q: searchParts.join(", "),
            format: "json",
            limit: 1,
            addressdetails: 1,
          },
          headers: {
            "User-Agent": "iService365-Hygiene-App",
          },
        },
      )
      .then((data) => (data?.length ? data[0] : null));
  }

  return {
    getCountries,
    getAddressByPostalCode,
    searchLocationByAddress,
  };
}
