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

interface AuthState {
  isAuthenticated: boolean;
  userId: number | null;
  username: string | null;
  loading: boolean;
}

const initialState: AuthState = {
  isAuthenticated: localStorage.getItem("isAuthenticated") === "true",
  userId: null,
  username: localStorage.getItem("username") || null,
  loading: false,
};

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    setAuth: (
      state,
      action: PayloadAction<{ userId: number; username: string }>
    ) => {
      state.isAuthenticated = true;
      state.userId = action.payload.userId;
      state.username = action.payload.username;
      localStorage.setItem("isAuthenticated", "true");
      localStorage.setItem("username", action.payload.username);
    },
    clearAuth: (state) => {
      state.isAuthenticated = false;
      state.userId = null;
      state.username = null;
      localStorage.removeItem("isAuthenticated");
      localStorage.removeItem("username");
    },
  },
});

export const { setAuth, clearAuth } = authSlice.actions;
export default authSlice.reducer;
