const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:4000';

const handleResponse = async (response) => {
  const contentType = response.headers.get('content-type');
  const isJson = contentType && contentType.includes('application/json');
  const data = isJson ? await response.json() : await response.text();
  if (!response.ok) {
    const message = (isJson && data?.message) || 'Beklenmeyen bir hata oluştu.';
    throw new Error(message);
  }
  return data;
};

export const apiClient = async (path, { method = 'GET', data, token } = {}) => {
  const headers = { 'Content-Type': 'application/json' };
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const response = await fetch(`${API_BASE_URL}${path}`, {
    method,
    headers,
    body: data ? JSON.stringify(data) : undefined,
  });

  return handleResponse(response);
};
