export class ApiClientError extends Error {
  status?: number;
  details?: unknown;
  causeError?: unknown;

  constructor(
    message: string,
    options?: { status?: number; details?: unknown; causeError?: unknown }
  ) {
    super(message);
    this.name = 'ApiClientError';
    this.status = options?.status;
    this.details = options?.details;
    this.causeError = options?.causeError;
  }
}

export type ErrorHandlers = {
  onForbidden?: (error: ApiClientError) => void | Promise<void>;
  onUnauthorized?: (error: ApiClientError) => void | Promise<void>;
  onError?: (error: ApiClientError) => void | Promise<void>;
};

const handlers: ErrorHandlers = {};

export const apiBaseUrl =
  import.meta.env.VITE_API_BASE_URL?.trim() ||
  (import.meta.env.DEV ? 'http://localhost:3000' : window.location.origin);

export function configureApiClient(nextHandlers: ErrorHandlers) {
  handlers.onForbidden = nextHandlers.onForbidden;
  handlers.onUnauthorized = nextHandlers.onUnauthorized;
  handlers.onError = nextHandlers.onError;
}

export { handlers };
