import { useQuery } from "@tanstack/react-query";
import ky from "ky";
import { useLocationSearch } from "@/hooks/useLocationSearch";
import { parseLangParam } from "@/lib/urlLang";
import { queryKeys } from "@/queries/keys";

const COUNTRY_CODE_URL = "https://stream.graff.tech/api/getCountryCode";

export async function fetchCountryCode(): Promise<{ countryCode: string }> {
  return ky.get(COUNTRY_CODE_URL).json<{ countryCode: string }>();
}

export function useCountryCodeQuery() {
  const search = useLocationSearch();
  const langFromUrl = parseLangParam(
    new URLSearchParams(search).get("lang")
  );

  return useQuery({
    queryKey: queryKeys.countryCode,
    queryFn: fetchCountryCode,
    enabled: langFromUrl === null,
    staleTime: 24 * 60 * 60 * 1000,
    retry: 2,
  });
}
