import isEqual from 'lodash.isequal';
import { createReducer } from '@reduxjs/toolkit';
import { IAuthorizationState , IAuthorizationPayload} from '../../../typescript/redux/authorization/interfaces';
import {
  actionLogInSuccess,
  actionLogInReject,
  actionLogOutSuccess,
  actionLogOutReject,
  actionCurrentSuccess,
  actionCurrentReject
} from '../action';

const initialState:IAuthorizationState = {
  name: "",
  lastName: "",
  originalName: "",
  originalLastName: "",
  avatarUrl: "",
  avatarsArr: [],
  color: "",
  code: "",
  _id: "",
  token: "",
  online: "",
  number: "" ,
  country: "",
  sort: false,
  nightMode: false,
  createdAt: "",
  updatedAt: "",
  __v: 0,
}

const reducerAuthorization = createReducer(initialState, {
  [actionLogInSuccess.type]: (state, { payload:token }: { payload: string }) => {
    return {...state,token};
  },
  [actionLogInReject.type]: (state, _payload) => {
    return state;
  },
  [actionLogOutSuccess.type]: (_state, _payload) => {
    return initialState;
  },
  [actionLogOutReject.type]: (state, _payload) => {
    return state;
  },
  [actionCurrentSuccess.type]: (state, { payload }: IAuthorizationPayload) => {
    if (isEqual(state, payload) === false) return payload
    return state;
  },
  [actionCurrentReject.type]: (_state, _payload) => {
    return initialState;
  },
});

export default reducerAuthorization;
