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

export interface TypingUser {
  chat_id: number;
  typing: boolean;
  user_id: number;
}

export interface TypingUserList {
  typingUserList: TypingUser[];
}

const initialState: TypingUserList = { typingUserList: [] };

const TypingUserListSlice = createSlice({
  name: "TypingUserList",
  initialState,
  reducers: {
    updateTypingUserList(state, action: PayloadAction<TypingUserList>) {
      return action.payload;
    },

    addTypingUser(state, action: PayloadAction<TypingUser>) {
      const exists = state.typingUserList.some(
        (user) =>
          user.chat_id === action.payload.chat_id &&
          user.user_id === action.payload.user_id
      );
      if (!exists) {
        state.typingUserList.push(action.payload);
      }
    },

    removeTypingUser(
      state,
      action: PayloadAction<{ chat_id: number; user_id: number }>
    ) {
      state.typingUserList = state.typingUserList.filter(
        (user) =>
          !(
            user.chat_id === action.payload.chat_id &&
            user.user_id === action.payload.user_id
          )
      );
    },
  },
});

export default TypingUserListSlice.reducer;
export const {
  updateTypingUserList,
  addTypingUser,
  removeTypingUser,
} = TypingUserListSlice.actions;
