import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import type { LoginState } from "./state";
import { loginAsync } from "./operations";

const initialState: LoginState = {
  apps: {
    LoginApiCallStatus: "none",
    localStorageKeyforIdToken: null,
  },
};

export const loginSlice = createSlice({
  name: "login",
  initialState,
  reducers: {
    changeLocalStorageKeyforIdToken: (
      state,
      action: PayloadAction<{ localStorageKeyforIdToken: string }>
    ) => {
      const { localStorageKeyforIdToken } = action.payload;
      state.apps.localStorageKeyforIdToken = localStorageKeyforIdToken;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(loginAsync.pending, (state) => {
      state.apps.LoginApiCallStatus = "pending";
    });
    builder.addCase(loginAsync.fulfilled, (state) => {
      state.apps.LoginApiCallStatus = "fulfilled";
    });
    builder.addCase(loginAsync.rejected, (state) => {
      state.apps.LoginApiCallStatus = "rejected";
    });
  },
});

export const { changeLocalStorageKeyforIdToken } = loginSlice.actions;
export default loginSlice.reducer;
