import { redirectToLoginAfterSessionExpired } from "@/features/auth/service/auth-service";

const baseURL = process.env.NEXT_PUBLIC_API_URL;

export async function baseAPI(path: string, options: RequestInit = {}) {
  const headers = new Headers(options.headers);
  const isMultipartRequest =
    typeof FormData !== "undefined" && options.body instanceof FormData;

  // FormData needs the browser-generated multipart boundary. Setting a JSON
  // content type here would make uploaded files unreadable by the backend.
  if (!isMultipartRequest && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  const res = await fetch(`${baseURL}${path}`, {
    ...options,
    credentials: "include",
    headers,
  });

  if (!res.ok) {
    if (res.status === 401) {
      redirectToLoginAfterSessionExpired();
    }

    let message = `API Error: ${res.status}`;

    try {
      const body = (await res.json()) as {
        message?: string;
        errors?: string[];
      };

      if (Array.isArray(body.errors) && body.errors.length > 0) {
        message = body.errors.join(", ");
      } else if (body.message) {
        message = body.message;
      }
    } catch {
      // Keep the generic status message when the body is not JSON.
    }

    throw new Error(message);
  }

  return res.json();
}
