/* eslint-disable @typescript-eslint/no-explicit-any */
import { authAPI } from '@/rtk/services/auth'
import { getResponseError } from '@/rtk/helpers/transformErrorMessage'
import { error, start, success } from '@/rtk/slices/auth'
import { removeTokens, setTokens } from '@/rtk/localStorage'
export const login =
  (formData: any, toast?: any, navigate?: any) => async (dispatch: any) => {
    dispatch(start())
    try {
      await authAPI.login(formData).then((res: { data: any }) => {
        if (res.data.status) {
          setTokens({ user: res.data })
          dispatch(success({ user: res.data }))
          navigate('/')
        } else {
          toast.show({
            title: 'Error',
            message: res.data.message,
            color: 'red',
          })
          dispatch(error({ error: res.data.message }))
        }
      })
    } catch (err: any) {
      toast.show({
        title: 'Error',
        message: getResponseError(err),
        color: 'red',
      })
      dispatch(error({ error: err }))
    }
  }

export const logout = (navigate?: any) => async (dispatch: any) => {
  dispatch(start())
  try {
    await authAPI.logout().then((res: { data: any }) => {
      if (res.data.status) {
        removeTokens()
        dispatch(success({ user: null }))
        navigate('/login')
      }
    })
  } catch (err: any) {
    removeTokens()
    dispatch(success({ user: null }))
    navigate('/login')
  }
}
