import { getSession } from 'next-auth/react';

function getTenantIdFromCookie(): string | null {
  if (typeof document === 'undefined') {
    return null;
  }

  try {
    const cookies = document.cookie.split(';');
    for (const cookie of cookies) {
      const [name, value] = cookie.trim().split('=');
      if (name === 'X-Tenant-Id') {
        return decodeURIComponent(value);
      }
    }
  } catch {
    // Cookie parsing may fail in some environments
  }

  return null;
}

export async function apiClient(
  url: string,
  options: RequestInit = {}
): Promise<Response> {
  const session = await getSession();
  const tenantId = getTenantIdFromCookie();

  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...(options.headers as Record<string, string>),
  };

  if (session?.accessToken) {
    headers['Authorization'] = `Bearer ${session.accessToken}`;
  }

  if (tenantId) {
    headers['X-Tenant-Id'] = tenantId;
  }

  return fetch(url, {
    ...options,
    headers,
  });
}
