import * as Sentry from '@sentry/react-native';
import type { NavigationContainerRef } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';

export const setupGlobalErrorHandler = (
  navigationRef: React.RefObject<NavigationContainerRef<any>>
) => {
  ErrorUtils.setGlobalHandler(async (error: any, isFatal?: boolean) => {
    Sentry.captureException(error);
    await Sentry.flush();

    if (isFatal && navigationRef.current?.reset) {
      navigationRef.current.reset({
        index: 0,
        routes: [{ name: NAVIGATION_PAGES.IN_APP_MAP_TAB }]
      });
    }
  });

  process.on?.('unhandledRejection', (reason: any) => {
    Sentry.captureException(reason);
  });
};
