/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-duplicate-imports */
import type { PayloadAction } from '@reduxjs/toolkit'
import { createSlice } from '@reduxjs/toolkit'
import { getAccessToken, getUser } from '@/rtk/localStorage'
import type { RootState } from '@/rtk/store'

export interface IAuthentication {
  isProcessingRequest: boolean
  user?: any
  token?: string
}
const initialState: IAuthentication = {
  isProcessingRequest: false,
  user:
    getUser() !== 'undefined' || getUser() !== null
      ? JSON.parse(getUser())
      : null,
  token: getAccessToken() ? getAccessToken() : '',
}
export const authenticationSlice = createSlice({
  name: 'authentication',
  initialState,
  reducers: {
    start: (state: any) => {
      return {
        ...state,
        isProcessingRequest: false,
      }
    },
    success: (state: any, action: PayloadAction<any>) => {
      return {
        ...state,
        ...action.payload,
        isProcessingRequest: false,
      }
    },
    error: (state: any, action: PayloadAction<any>) => {
      return {
        ...state,
        ...action.payload,
        isProcessingRequest: false,
      }
    },
  },
})

export const { start, success, error } = authenticationSlice.actions
export const selectAuthentication = (state: RootState) => state.authentication
export const authenticationReducer = authenticationSlice.reducer
