const BASE_URL = '/api';

export async function apiClient<T>(endpoint: string, options?: RequestInit): Promise<T> {
  const isServer = typeof window === 'undefined';
  const requestHeaders = isServer ? await (await import('next/headers')).headers() : null;
  const host = requestHeaders?.get('x-forwarded-host') ?? requestHeaders?.get('host');
  const protocol = requestHeaders?.get('x-forwarded-proto') ?? 'http';
  const origin = isServer && host ? `${protocol}://${host}` : '';
  const optionHeaders = options?.headers;
  const restOptions = options ? { ...options } : null;

  if (restOptions && 'headers' in restOptions) {
    delete restOptions.headers;
  }

  const res = await fetch(`${origin}${BASE_URL}${endpoint}`, {
    ...restOptions,
    headers: {
      'Content-Type': 'application/json',
      ...(isServer && requestHeaders?.get('cookie')
        ? { cookie: requestHeaders.get('cookie') as string }
        : {}),
      ...optionHeaders
    }
  });

  if (!res.ok) {
    throw new Error(`API error: ${res.status} ${res.statusText}`);
  }

  return res.json() as Promise<T>;
}
