import { createSlice, PayloadAction } from "@reduxjs/toolkit";

type AuthState = {
  token: string | null;
};

const initialState: AuthState = {
  token: localStorage.getItem("token"), // Load token from localStorage
}; 

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    setToken: (state, action: PayloadAction<string>) => {
      state.token = action.payload;
      localStorage.setItem("token", action.payload); // ✅ Store token in localStorage
    },
    logout: (state) => {
      state.token = null;
      localStorage.removeItem("token"); // ✅ Remove token from localStorage on logout
    },
  },
});

export const { setToken, logout } = authSlice.actions;
export default authSlice.reducer;
