import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import type { RootState } from "../../store";
import { UserResponse } from "./type";

type AuthState = UserResponse | null;

const slice = createSlice({
  name: "auth",
  initialState: null as AuthState,
  reducers: {
    setCredentials: (state, action: PayloadAction<AuthState>) => {
      state = action.payload;
      return state;
    },
    logOut: (state) => {
      window.localStorage.setItem("authUser", "");

      state = null;
      return state;
    },
  },
});

export const { setCredentials, logOut } = slice.actions;

export default slice.reducer;

export const selectCurrentUser = (state: RootState) => state.auth;
