import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { OnlineUser, OnlineUserRes } from "../../types/OnlineUserType";

const initialState: OnlineUserRes = { onlineUsers: [] };

// Create a slice of the state
const OnlineUserSlice = createSlice({
  name: "OnlineUserList",
  initialState,
  reducers: {
    initialOnlineUser(state, action: PayloadAction<OnlineUserRes>) {
      return action.payload;
    },
    addOnlineUser(state, action: PayloadAction<OnlineUser>) {
      state.onlineUsers.push(action.payload);
    },
    removeOnlineUser(state, action: PayloadAction<number>) {
      state.onlineUsers = state.onlineUsers.filter(
        (user) => user.user_id != action.payload,
      );
    },
  },
});

// Export the reducer and actions
export default OnlineUserSlice.reducer;
export const { initialOnlineUser, addOnlineUser, removeOnlineUser } =
  OnlineUserSlice.actions;
