export const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8029/api/v1";

export class ApiError extends Error {
  status: number;
  errors?: Record<string, string[]>;
  /** The full JSON error body, for endpoints that return extra fields. */
  data?: Record<string, unknown>;

  constructor(
    message: string,
    status: number,
    errors?: Record<string, string[]>,
    data?: Record<string, unknown>,
  ) {
    super(message);
    this.name = "ApiError";
    this.status = status;
    this.errors = errors;
    this.data = data;
  }
}

/** True for a `fetch` failure caused by no connectivity, as opposed to an HTTP error response. */
export function isNetworkError(error: unknown): boolean {
  return error instanceof TypeError;
}

interface RequestOptions {
  method?: string;
  token?: string | null;
  body?: BodyInit | null;
  headers?: Record<string, string>;
}

async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
  const headers: Record<string, string> = { Accept: "application/json", ...options.headers };
  if (options.token) {
    headers.Authorization = `Bearer ${options.token}`;
  }

  const response = await fetch(`${API_BASE_URL}${path}`, {
    method: options.method ?? "GET",
    headers,
    body: options.body ?? undefined,
  });

  const contentType = response.headers.get("content-type") ?? "";
  const payload = contentType.includes("application/json") ? await response.json() : null;

  if (!response.ok) {
    throw new ApiError(
      payload?.message ?? `Request failed with status ${response.status}`,
      response.status,
      payload?.errors,
      payload ?? undefined,
    );
  }

  return payload as T;
}

export const apiClient = {
  get: <T>(path: string, token?: string | null) => request<T>(path, { token }),

  postJson: <T>(path: string, body: unknown, token?: string | null) =>
    request<T>(path, {
      method: "POST",
      token,
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" },
    }),

  putJson: <T>(path: string, body: unknown, token?: string | null) =>
    request<T>(path, {
      method: "PUT",
      token,
      body: JSON.stringify(body),
      headers: { "Content-Type": "application/json" },
    }),

  postForm: <T>(path: string, formData: FormData, token?: string | null) =>
    request<T>(path, { method: "POST", token, body: formData }),
};
