import { getToken } from "@/auth/AuthProvider";

export class ApiError extends Error {
  constructor(
    public readonly status: number,
    public readonly type: string,
    message: string
  ) {
    super(message);
    this.name = "ApiError";
  }
}

export async function apiFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
  const token = getToken();

  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    ...(options.headers as Record<string, string>),
  };

  if (token) {
    headers["Authorization"] = `Bearer ${token}`;
  }

  const res = await fetch(path, { ...options, headers });

  if (!res.ok) {
    let type = "api_error";
    let message = `HTTP ${res.status}`;
    try {
      const body = await res.json();
      if (body?.error) {
        type = body.error.type ?? type;
        message = body.error.message ?? message;
      }
    } catch {
      // ignore parse error
    }
    throw new ApiError(res.status, type, message);
  }

  if (res.status === 204) return undefined as T;
  return res.json() as Promise<T>;
}
