import { logger } from 'tachyon-logger/defaultLogger';
import { singleStringLoggerMiddleware } from 'tachyon-logger/loggerMiddleware';
import { SentinelLogger } from 'tachyon-logger/sentinelLogger';

/**
 * Setup client-side logging for all uncaught errors and report to Sentinel.
 */
export function setupClientErrorHandling(
  buildId: string,
  deviceId: string,
  pageSessionId: string,
): void {
  setOnErrorHandler();
  registerSentinelLogger(buildId, deviceId, pageSessionId);
}

/**
 * Register a logger that will report error level logs to Sentinel.
 */
export function registerSentinelLogger(
  buildID: string,
  deviceID: string,
  pageSessionID: string,
): void {
  logger.register(
    new SentinelLogger({
      buildID,
      deviceID,
      pageSessionID,
      middleware: [singleStringLoggerMiddleware],
    }),
  );
}

/**
 * Use window.onerror to log all client-side errors.
 */
export function setOnErrorHandler(): void {
  window.onerror = (message, source, lineno, colno, error) => {
    logger.error({
      colno,
      error,
      lineno,
      message,
      source,
    });
  };
}
