const getApiUrl = () => {
  if (typeof window !== 'undefined') {
    // If accessed via an IP address (like 192.168.1.25) or domain, use that host on port 3001
    const { hostname, protocol } = window.location;
      return `${protocol}//${hostname}:8002`;
  }
    return 'http://localhost:8002';
};

// Use the build-time NEXT_PUBLIC_API_URL when provided, but prefer a runtime-derived
// host when the app is running in the browser. This prevents the bundle from pointing
// at `localhost` (which is wrong for remote users) when the frontend was built inside
// the Compose network.
const rawEnvUrl = process.env.NEXT_PUBLIC_API_URL;
const API_URL = (typeof window !== 'undefined')
  ? (rawEnvUrl && !/localhost|127\.0\.0\.1/.test(rawEnvUrl) ? rawEnvUrl : getApiUrl())
  : (rawEnvUrl || getApiUrl());

export async function apiRequest<T = any>(
  endpoint: string,
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' = 'GET',
  body?: any,
): Promise<T> {
  const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
  
  const headers: Record<string, string> = {};
  
  if (!(body instanceof FormData)) {
    headers['Content-Type'] = 'application/json';
  }

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

  const response = await fetch(`${API_URL}/${endpoint.replace(/^\//, '')}`, {
    method,
    headers,
    body: body ? (body instanceof FormData ? body : JSON.stringify(body)) : undefined,
  });

  if (!response.ok) {
    let errorMsg = `Request failed with status ${response.status}`;
    try {
      const errJson = await response.json();
      if (typeof errJson.message === 'string') {
        errorMsg = errJson.message;
      } else if (Array.isArray(errJson.message)) {
        errorMsg = errJson.message.join(', ');
      } else if (errJson.reason) {
        errorMsg = `${errJson.reason}${errJson.action ? ` - ${errJson.action}` : ''}`;
      } else if (errJson.error) {
        errorMsg = errJson.error;
      }
    } catch {
      // JSON parsing failed (e.g. HTML error page or empty response)
    }
    throw new Error(errorMsg);
  }

  // Handle empty responses
  if (response.status === 204) {
    return {} as T;
  }

  return response.json();
}
