import { ApiError } from '@agiliza/api/domain'
import { ErrorTypes } from '@agiliza/constants/error'
import * as ucLogout from '@agiliza/redux/ui/login'
import { Middleware, PayloadAction, ThunkDispatch } from '@reduxjs/toolkit'

import { actions as errorActions } from './ui/error'

// export const errorMiddleware: Middleware =
//   ({ dispatch }) =>
//   (next: Dispatch<PayloadAction<any>>) =>
//     ((action: PayloadAction<any>) => {
//       if (/Error$/.test(action.type) && action.payload) {
//         const error = getError(action.payload)
//         dispatch(errorActions.setErrorMessage(error))
//       }
//       return next(action)
//     }) as Dispatch<PayloadAction>

export const errorMiddleware: Middleware = (api) => (next: ThunkDispatch<any, any, any>) => (action: PayloadAction<ApiError>) => {
  if (action.type.includes('/rejected')) {
    const error = action.payload
    // console.log(action);
    // console.log(error)
    // Todo erro de sessão expirada deve imediatamente remover a autenticação do usuário.
    if (error.type === ErrorTypes.EXPIRED_SESSION) {
      api.dispatch(ucLogout.actions.logout() as any)
    } else if (!action.type.includes('/connect') && (action.type.includes('useCases') || action.type.includes('ui'))) {
      if (error.type !== ErrorTypes.FORM_VALIDATION && error.type !== ErrorTypes.MISSING_INPUT) {
        api.dispatch(errorActions.setErrorMessage(error.message || 'Erro de autenticação'))
      }
    }
  }
  return next(action)
}

export const printMiddleware: Middleware =
  (api) => (next: ThunkDispatch<any, any, any>) => (action: PayloadAction<any, string, { arg: Record<string, unknown> | string }>) => {
    if (action.type.includes('/pending')) {
      console.log(
        `%c ${action.type.substring(0, action.type.lastIndexOf('/'))} %c`,
        `color: white; font-weight: bolder; background: blue`,
        'font-weight: bolder; font-style: italic;',
        action.meta.arg || ''
      )
    }
    if (action.type.includes('/fulfilled')) {
      console.log(
        `%c ${action.type.substring(0, action.type.lastIndexOf('/'))} %c`,
        `color: white; font-weight: bolder; background: green`,
        'font-weight: bolder; font-style: italic;',
        action.payload ? (typeof action.payload === 'object' ? (Object.keys(action.payload).length !== 0 ? action.payload : '') : action.payload) : ''
      )
    }
    return next(action)
  }
