export class ApiError extends Error {
  constructor(
    public status: number,
    message: string,
    public data?: unknown,
  ) {
    super(message);
    this.name = 'ApiError';
  }
}

let unauthorizedHandler: (() => void) | null = null;

export function setUnauthorizedHandler(handler: (() => void) | null) {
  unauthorizedHandler = handler;
}


export function getApiBaseUrl(): string {
  if (typeof window !== 'undefined') {
    return '/api';
  }
  const configured = process.env.BACKEND_URL?.trim();
  if (!configured) {
    throw new Error('BACKEND_URL environment variable is not defined');
  }
  return configured;
}

function extractErrorMessage(body: unknown, status: number): string {
  if (body && typeof body === 'object') {
    const record = body as Record<string, unknown>;
    const raw = record.error ?? record.message;

    if (typeof raw === 'string' && raw.trim()) {
      return raw;
    }
    if (Array.isArray(raw) && raw.length > 0) {
      return raw.map(String).join('. ');
    }
    if (raw && typeof raw === 'object' && 'message' in raw) {
      const nested = (raw as { message?: unknown }).message;
      if (typeof nested === 'string' && nested.trim()) {
        return nested;
      }
      if (Array.isArray(nested) && nested.length > 0) {
        return nested.map(String).join('. ');
      }
    }
  }
  return `Request failed with status ${status}`;
}

export async function apiRequest<T = unknown>(endpoint: string, options: RequestInit = {}): Promise<T> {
  const isFormData = typeof FormData !== 'undefined' && options.body instanceof FormData;
  const headers: Record<string, string> = {
    ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
    ...(options.headers as Record<string, string>),
  };

  const baseUrl = getApiBaseUrl();
  const url = endpoint.startsWith('http') ? endpoint : `${baseUrl}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;

  let response: Response;
  try {
    response = await fetch(url, {
      ...options,
      headers,
      credentials: 'include',
    });
  } catch {
    throw new ApiError(0, 'Unable to connect to the server. Please check your connection and try again.');
  }

  const body = await response.json().catch(() => null);

  if (!response.ok) {
    const errorMsg = extractErrorMessage(body, response.status);
    const isPublicAuthEndpoint = endpoint.startsWith('/auth/login') || endpoint.startsWith('/auth/forgot-password') || endpoint.startsWith('/auth/reset-password') || endpoint.startsWith('/auth/accept-invite') || endpoint.startsWith('/auth/logout');

    if (response.status === 401 && !isPublicAuthEndpoint && unauthorizedHandler) {
      unauthorizedHandler();
    }

    throw new ApiError(response.status, errorMsg, body);
  }

  // Response wrapped in standard { data: ... }
  return body?.data !== undefined ? body.data : body;
}
