const API_BASE = import.meta.env.VITE_API_BASE || '';

export function createApi(getToken, onUnauthorized) {
  async function request(path, options = {}) {
    const token = getToken();
    const isFormData = options.body instanceof FormData;
    const method = options.method || 'GET';
    const url = `${API_BASE}${path}`;
    let response;
    try {
      response = await fetch(url, {
        ...options,
        headers: {
          ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
          ...(options.headers || {})
        }
      });
    } catch (err) {
      const detail = err?.message ? `: ${err.message}` : '';
      const error = new Error(`${method} ${path} could not reach the API${detail}`);
      error.path = path;
      error.method = method;
      error.cause = err;
      throw error;
    }
    if (response.status === 401) onUnauthorized?.();
    if (response.status === 204) return null;
    const data = await response.json().catch(() => ({}));
    if (!response.ok) {
      const error = new Error(data.error || `Request failed: ${response.status}`);
      error.status = response.status;
      error.payload = data;
      error.path = path;
      error.method = method;
      throw error;
    }
    return data;
  }

  return {
    get: (path) => request(path),
    post: (path, body) => request(path, { method: 'POST', body: JSON.stringify(body) }),
    postForm: (path, body) => request(path, { method: 'POST', body }),
    put: (path, body) => request(path, { method: 'PUT', body: JSON.stringify(body) }),
    delete: (path) => request(path, { method: 'DELETE' })
  };
}
