import { RequestError } from 'src/types/services';

const unaffectedRoutes: Array<string | RegExp> = [
  '/people-experience',
  '/time-tracking/report',
  'notification-center',
  'workflows',
  '/ai-chatbot',
  '/marty/calls',
  'celebrations/',
  /^events\/\d+\/organizers/, // workaround, remove when backend fix is ready,
  '/microloans',
  '/prode',
];

const matchesUnaffectedRoute = (url: string, route: string | RegExp) =>
  route instanceof RegExp ? route.test(url) : url.startsWith(route);

export const isRedirectError = (error: RequestError) => {
  // If the error is not an axios error, return false
  // AbortController error is not an axios error
  if (!error.config) {
    return false;
  }

  const { config } = error;

  if (
    config.method !== 'get' ||
    unaffectedRoutes.some(
      route => config.url && matchesUnaffectedRoute(config.url, route),
    )
  ) {
    return false;
  }

  return (
    error.response?.status === 404 ||
    (error.response?.status === 400 &&
      error.response?.data?.message === 'Invalid id format')
  );
};
