import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ConnectedUser } from "../../types/ResType";

const initialState: ConnectedUser[] = [];

// Create a slice of the state
const ConnectedUserSlice = createSlice({
  name: "ConnectedUser",
  initialState,
  reducers: {
    updateConnectedUserList(state, action: PayloadAction<ConnectedUser[]>) {
      return action.payload;
    },
    addConnectedUser(state, action: PayloadAction<ConnectedUser>) {
      const exists = state.some((user) => user.user_id === action.payload.user_id);
      if (!exists) {
        return [...state, action.payload];
      }
      return state;
    },
    removeConnectedUser(state, action: PayloadAction<number>) {
      return state.filter((user) => user.user_id !== action.payload);
    },
  },
});

// Export the reducer and actions
export default ConnectedUserSlice.reducer;
export const {
  updateConnectedUserList,
  removeConnectedUser,
  addConnectedUser,
} = ConnectedUserSlice.actions;
