import { QueryClient, QueryFunction } from "@tanstack/react-query";
import { API_URL } from "./constants";

async function throwIfResNotOk(res: Response) {
  if (!res.ok) {
    const text = (await res.text()) || res.statusText;
    throw new Error(`${res.status}: ${text}`);
  }
}

export async function apiRequest(
  method: string,
  endpoint: string,
  data?: unknown | undefined
): Promise<Response | string> {
  const res = await fetch(`${API_URL}${endpoint}`, {
    method,
    headers: data ? { "Content-Type": "application/json" } : {},
    body: data ? JSON.stringify(data) : undefined,
    credentials: "include",
  });
  if (!res.ok) {
    const errorText = await res.text();
    throw new Error(errorText || "Request failed");
  }

  const contentType = res.headers.get("Content-Type") || "";
  if (contentType.includes("application/json")) {
    return await res.json();
  }
  // await throwIfResNotOk(res);

  // return await res.json();
  return await res.text();
}

type UnauthorizedBehavior = "returnNull" | "throw";
export const getQueryFn: <T>(options: {
  on401: UnauthorizedBehavior;
}) => QueryFunction<T> =
  ({ on401: unauthorizedBehavior }) =>
  async ({ queryKey }) => {
    //  Ensure the first element of queryKey is a string representing the endpoint
    if (typeof queryKey[0] !== "string") {
      throw new Error(
        "Query key must start with a string representing the endpoint."
      );
    }
    let url = `${API_URL}${queryKey[0]}`;
    if (queryKey[1] && typeof queryKey[1] === "object") {
      const params = new URLSearchParams(
        queryKey[1] as Record<string, string>
      ).toString();
      if (params) {
        url += (url.includes("?") ? "&" : "?") + params;
      }
    }

    const res = await fetch(url, {
      credentials: "include",
    });

    if (unauthorizedBehavior === "returnNull" && res.status === 401) {
      return null;
    }

    await throwIfResNotOk(res);
    return await res.json();
  };

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      queryFn: getQueryFn({ on401: "throw" }),
      refetchInterval: false,
      refetchOnWindowFocus: false,
      staleTime: Infinity,
      retry: false,
    },
    mutations: {
      retry: false,
    },
  },
});
