import type { Logger } from './logger';

/**
 * Install global error handlers that route uncaught errors to the logger.
 *
 * Captures:
 * - window.onerror (uncaught exceptions)
 * - window.onunhandledrejection (unhandled promise rejections)
 *
 * Call once at app init. Returns a cleanup function.
 */
export function installGlobalHandlers(logger: Logger): () => void {
  const onError = (event: ErrorEvent) => {
    logger.error('Uncaught exception', event.error ?? new Error(event.message), {
      source: event.filename,
      line: event.lineno,
      col: event.colno,
    });
  };

  const onRejection = (event: PromiseRejectionEvent) => {
    const err = event.reason instanceof Error
      ? event.reason
      : new Error(String(event.reason));
    logger.error('Unhandled promise rejection', err);
  };

  window.addEventListener('error', onError);
  window.addEventListener('unhandledrejection', onRejection);

  return () => {
    window.removeEventListener('error', onError);
    window.removeEventListener('unhandledrejection', onRejection);
  };
}
