import { createSlice } from "@reduxjs/toolkit";
import { fetchAuthenticationCode } from "./authThunks";

const initialState = {
  accessToken: null,
  isLoading: false,
  error: null,
};

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchAuthenticationCode.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(fetchAuthenticationCode.fulfilled, (state, action) => {
        state.accessToken = action.payload;
        state.isLoading = false;
      })
      .addCase(fetchAuthenticationCode.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      });
  },
});

export const selectAccessToken = (state) => state.auth.accessToken;
export const selectAuthLoading = (state) => state.auth.isLoading;
export const selectAuthError = (state) => state.auth.error;

export default authSlice.reducer;
