/* eslint-disable prettier/prettier */
import {createAsyncThunk, createSlice} from '@reduxjs/toolkit';

import serviceRequest from '../../app/serviceRequest';

import homeAPI from '../../api/homeAPI';
import Utils from '../../utils';

const initialHome = {
  quotationList: [],
  news: [],
  birthdayListInMonth: [],
};

export const getQuotation = createAsyncThunk(
  'home/getQuotation',
  async (data, thunkAPI) => {
    return serviceRequest({
      dispatch: thunkAPI.dispatch,
      serviceMethod: homeAPI.requestGetQuotation,
      payload: data,
      options: {
        skipLoader: false,
      },
    });
  },
);
export const getRadomQuotation = createAsyncThunk(
  'home/getRadomQuotation',
  async (data, thunkAPI) => {
    return serviceRequest({
      dispatch: thunkAPI.dispatch,
      serviceMethod: homeAPI.requestGetRandomQuotation,
      payload: data,
      options: {
        skipLoader: false,
      },
    });
  },
);
export const getUserDirectManagers = createAsyncThunk(
  'home/getUserDirectManagers',
  async (data, thunkAPI) => {
    return serviceRequest({
      dispatch: thunkAPI.dispatch,
      serviceMethod: homeAPI.requestGetUsersDirectManagers,
      payload: data,
      options: {
        skipLoader: false,
      },
    });
  },
);
export const getBirthDayUser = createAsyncThunk(
  'home/getBirthDayUser',
  async (data, thunkAPI) => {
    return serviceRequest({
      dispatch: thunkAPI.dispatch,
      serviceMethod: homeAPI.requestGetBirthdayUser,
      payload: data,
      options: {
        skipLoader: false,
      },
    });
  },
);

const homeSlice = createSlice({
  name: 'home',
  initialState: initialHome,
  reducers: {},
  extraReducers: builder => {
    builder.addCase(getQuotation.fulfilled, (state, action) => {
      const {success} = Utils.getValues(action, 'payload', false);
      console.log('action', action);
      if (success) {
        state.quotationList = Utils.getValues(
          action,
          'payload.data.collection',
          [],
        );
      }
    });
    builder.addCase(getRadomQuotation.fulfilled, (state, action) => {
      const {success} = Utils.getValues(action, 'payload', false);
      if (success) {
        state.randomQuotation = Utils.getValues(action, 'payload.data', null);
      }
    });
    builder.addCase(getBirthDayUser.fulfilled, (state, action) => {
      const {success} = Utils.getValues(action, 'payload', false);
      if (success) {
        state.birthdayListInMonth = Utils.getValues(action, 'payload.data', []);
      }
    });
  },
});

const {reducer} = homeSlice;
export default reducer;
