import * as Sentry from '@sentry/browser';
import { recordVaosError } from './events';
import environment from 'platform/utilities/environment';

export function captureError(
  err,
  skipRecordEvent = false,
  customTitle,
  extraData,
) {
  let eventErrorKey;

  if (err instanceof Error) {
    Sentry.captureException(err);
    eventErrorKey = err.message;
  } else {
    Sentry.withScope(scope => {
      scope.setExtra('error', err);
      if (extraData) {
        scope.setExtra('extraData', extraData);
      }
      const errorTitle =
        customTitle || err?.errors?.[0]?.title || err?.issue?.[0]?.code || err;
      const message = `vaos_server_error${errorTitle ? `: ${errorTitle}` : ''}`;
      eventErrorKey = message;
      // the apiRequest helper returns the errors array, instead of an exception
      Sentry.captureMessage(message);
    });
  }

  if (!skipRecordEvent) {
    recordVaosError(eventErrorKey);
  }

  if (!environment.isProduction()) {
    // eslint-disable-next-line no-console
    console.error(err);
  }
}

export function getErrorCodes(error) {
  return error?.errors?.map(e => e.code) || [];
}

export function has400LevelError(error) {
  return getErrorCodes(error).some(code => code.startsWith('VAOS_4'));
}

@@ -362,19 +362,50 @@
   %7D else
+ if (err?.issue %7C%7C err?.errors)
  %7B%0A
-
     Sent
@@ -586,24 +586,32 @@
 stomTitle %7C%7C
+%0A       
  err?.errors
@@ -621,24 +621,32 @@
 0%5D?.title %7C%7C
+%0A       
  err?.issue?
@@ -655,98 +655,595 @@
 0%5D?.
-code %7C%7C err;%0A      const message = %60vaos_server_error$%7BerrorTitle ? %60: $%7BerrorTitle%7D%60 : ''
+diagnostics %7C%7C%0A        err?.errors?.%5B0%5D?.code %7C%7C%0A        err?.issue?.%5B0%5D?.code %7C%7C%0A        err;%0A      const message = %60vaos_server_error$%7BerrorTitle ? %60: $%7BerrorTitle%7D%60 : ''%7D%60;%0A      eventErrorKey = message;%0A      // the apiRequest helper returns the errors array, instead of an exception%0A      Sentry.captureMessage(message);%0A    %7D);%0A  %7D else %7B%0A    Sentry.withScope(scope =%3E %7B%0A      scope.setExtra('error', err);%0A      if (extraData) %7B%0A        scope.setExtra('extraData', extraData);%0A      %7D%0A      const message = %60vaos_client_error$%7B%0A        customTitle ? %60: $%7BcustomTitle%7D%60 : ''%0A      
 %7D%60;%0A

Set a consistent error title for VAOS server errors (#14775)