export async function apiFetch(url: string, options: RequestInit = {}) {
  const start = performance.now();

  const token = typeof window !== "undefined" ? localStorage.getItem("token") : null;

  const response = await fetch(url, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(options.headers || {}),
    },
  });

  const duration = performance.now() - start;

  if (process.env.NODE_ENV === "development") {
    console.log(`%c[API] ${url} ${duration.toFixed(0)} ms`, `color:${getPerfColor(duration)}`);
  }

  if (!response.ok) {
    let message = `Erreur HTTP: ${response.status}`;

    try {
      const errorData = await response.json();

      if (errorData?.message) {
        message = Array.isArray(errorData.message)
          ? errorData.message.join(", ")
          : errorData.message;
      }
    } catch (_) { }

    throw new Error(message);
  }

  return response.json();
}

function getPerfColor(ms: number) {
  if (ms < 100) return "green";

  if (ms < 300) return "orange";

  return "red";
}