<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_ if (enableTranslation) { _%>
import { translate } from 'react-jhipster';
<%_ } _%>
import { toast } from 'react-toastify';
import { isFulfilledAction, isRejectedAction } from 'app/shared/reducers/reducer.utils';
import { isAxiosError } from 'axios';
import { FieldErrorVM, isProblemWithMessage } from 'app/shared/jhipster/problem-details';
import { getMessageFromHeaders } from 'app/shared/jhipster/headers';

type ToastMessage = {
  message?: string;
<%_ if (enableTranslation) { _%>
  key?: string;
  data?: any;
<%_ } _%>
};

const addErrorAlert = (message: ToastMessage) => {
<%_ if (enableTranslation) { _%>
  toast.error(message.key ? translate(message.key, message.data) ?? message.message : message.message);
<%_ } else { _%>
  toast.error(message.message);
<%_ } _%>
};

const getFieldErrorsToasts = (fieldErrors: FieldErrorVM[]): ToastMessage[] =>
  fieldErrors.map(fieldError => {
    if (['Min', 'Max', 'DecimalMin', 'DecimalMax'].includes(fieldError.message)) {
      fieldError.message = 'Size';
    }
    // convert 'something[14].other[4].id' to 'something[].other[].id' so translations can be written to it
    const convertedField = fieldError.field.replace(/\[\d*\]/g, '[]');
<%_ if (enableTranslation) { _%>
    const fieldName = translate(`<%= frontendAppName %>.${fieldError.objectName}.${convertedField}`);
    return { message: `Error on field "${fieldName}"`, key: `error.${fieldError.message}`, data: { fieldName } };
<%_ } else { _%>
    const fieldName = convertedField.charAt(0).toUpperCase() + convertedField.slice(1);
    return { message: `Error on field "${fieldName}"` };
<%_ } _%>
  });

// eslint-disable-next-line complexity
export default () => next => action => {
  const { error, payload } = action;

  /**
   *
   * The notification middleware serves to add success and error notifications
   */
  if (isFulfilledAction(action) && payload?.headers) {
    const { alert<% if (enableTranslation) { %>, param<% } %> } = getMessageFromHeaders(payload.headers);
    if (alert) {
<%_ if (enableTranslation) { _%>
      toast.success(translate(alert, { param }));
<%_ } else { _%>
      toast.success(alert);
<%_ } _%>
    }
  }

  if (isRejectedAction(action) && isAxiosError(error)) {
    if (error.response) {
      const { response } = error;
      if (response.status === 401) {
        // Ignore, page will be redirected to login.
      } else if (error.config?.url?.endsWith('api/account') || error.config?.url?.endsWith('api/authenticate')) {
        // Ignore, authentication status check and authentication are treated differently.
      } else if (response.status === 0) {
        // connection refused, server not reachable
          addErrorAlert({
            message: 'Server not reachable',
<%_ if (enableTranslation) { _%>
            key: 'error.server.not.reachable',
<%_ } _%>
          });
      } else if (response.status === 404) {
          addErrorAlert({
            message: 'Not found',
<%_ if (enableTranslation) { _%>
            key: 'error.url.not.found',
<%_ } _%>
          });
      } else {
        const { data } = response;
        const problem = isProblemWithMessage(data) ? data : null;
        if (problem?.fieldErrors) {
          getFieldErrorsToasts(problem.fieldErrors).forEach(message => addErrorAlert(message));
        } else {
          const { error: toastError<% if (enableTranslation) { %>, param<% } %> } = getMessageFromHeaders((response.headers as any) ?? {});
          if (toastError) {
<%_ if (enableTranslation) { _%>
            const entityName = translate('global.menu.entities.' + param);
            addErrorAlert({ key: toastError, data: { entityName } });
<%_ } else { _%>
            addErrorAlert({ message: toastError });
<%_ } _%>
<%_ if (enableTranslation) { _%>
          } else if (problem?.message) {
            addErrorAlert({ message: problem.detail, key: problem.message });
<%_ } _%>
          } else if (typeof data === 'string' && data !== '') {
            addErrorAlert({ message: data });
          } else {
            toast.error(data?.detail ?? data?.message ?? data?.error ?? data?.title ?? 'Unknown error!');
          }
        }
      }
    } else if (error.config?.url?.endsWith('api/account') && error.config?.method === 'get') {
      /* eslint-disable no-console */
      console.log('Authentication Error: Trying to access url api/account with GET.');
    } else {
      addErrorAlert({ message: error.message ?? 'Unknown error!' });
    }
  } else if (error) {
    addErrorAlert({ message: error.message ?? 'Unknown error!' });
  }

  return next(action);
};
