import { API_BASE_URL } from './apiConfig';

export async function apiClient(endpoint, options = {}) {
  const token = localStorage.getItem('session_token');

  // Extract body and method explicitly
  const method = (options.method || 'GET').toUpperCase();
  const rawBody = options.body;

  // Prepare base headers
  const headers = {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
    ...(options.headers || {}),
  };

  // Ensure body is stringified properly if present
  let formattedBody = null;
  if (rawBody !== undefined && rawBody !== null) {
    formattedBody = typeof rawBody === 'object' && !(rawBody instanceof FormData)
      ? JSON.stringify(rawBody)
      : rawBody;
  }

  // Construct final fetch options
  const fetchOptions = {
    method,
    credentials: 'include',
    headers,
  };

  if (method !== 'GET' && method !== 'HEAD' && formattedBody) {
    fetchOptions.body = formattedBody;
  }

  const formattedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;

  console.log(`[apiClient Dispatch] ${method} -> ${formattedEndpoint}`, fetchOptions.body);

  const response = await fetch(`${API_BASE_URL}${formattedEndpoint}`, fetchOptions);

  if (!response.ok) {
    let errorMessage = `HTTP Error ${response.status}`;
    try {
      const errJson = await response.json();
      errorMessage = errJson.message || errJson.error || errorMessage;
    } catch (e) {
      // Non-JSON response fallback
    }
    throw new Error(errorMessage);
  }

  return response.json();
}