const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL || '/api/proxy';

interface RequestOptions {
  method?: string;
  body?: unknown;
  headers?: Record<string, string>;
}

function getAuthHeaders(): Record<string, string> {
  if (typeof window === 'undefined') return {};
  const headers: Record<string, string> = {};

  const token = localStorage.getItem('access_token');
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const tenantData = localStorage.getItem('current_tenant');
  if (tenantData) {
    try {
      const tenant = JSON.parse(tenantData);
      headers['X-Tenant-Id'] = tenant.id;
    } catch {
      // ignore parse errors
    }
  }

  return headers;
}

export async function apiClient<T>(endpoint: string, options: RequestOptions = {}): Promise<T> {
  const { method = 'GET', body, headers = {} } = options;

  const response = await fetch(`${API_BASE}${endpoint}`, {
    method,
    headers: {
      'Content-Type': 'application/json',
      ...getAuthHeaders(),
      ...headers,
    },
    body: body ? JSON.stringify(body) : undefined,
  });

  if (!response.ok) {
    if (response.status === 401 && typeof window !== 'undefined') {
      localStorage.removeItem('access_token');
      localStorage.removeItem('refresh_token');
      localStorage.removeItem('current_tenant');
      window.location.href = '/login';
      throw new Error('Session expired');
    }
    const errorData = await response.json().catch(() => null);
    const message = errorData?.message || `${response.status} ${response.statusText}`;
    throw new Error(message);
  }

  return response.json();
}
