import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { CurrentConversationType } from "../../types/ChatListType";

const initialState: CurrentConversationType = {
  chat_id: -1,
  chat_type: "private",
  full_name: "",
  group_name: "",
  mobile_num: "",
  profile_pic: "",
  user_id: 0,
  user_name: "",
  email_id: "",
  createdAt: new Date(),
  updatedAt: new Date(),
  group_description: "",
  group_icon: "",
  is_group_blocked: false,
  other_user_blocked_you: false,
  unseen_count: 0,
  bio: "",
  is_message_list_empty: true,
  is_archived: false,
  is_conversation_changed: Math.random(),
};

// Create a slice of the state
const CurrentConversationSlice = createSlice({
  name: "CurrentConversation",
  initialState,
  reducers: {
    // Reducer to update the CurrentConversation
    updateCurrentConversation(
      state,
      action: PayloadAction<Partial<CurrentConversationType>>,
    ) {
      sessionStorage.setItem(
        "currentConversation",
        JSON.stringify({ ...state, ...action.payload }),
      );
      console.log({ ...state, ...action.payload },"{ ...state, ...action.payload }");
      
      return { ...state, ...action.payload };
    },
    // Reducer to reset the CurrentConversation to the initial state
    resetCurrentConversation() {
      sessionStorage.removeItem("currentConversation");
      return initialState;
    },
  },
});

// Export the reducer and actions
export default CurrentConversationSlice.reducer;

export const { updateCurrentConversation, resetCurrentConversation } =
  CurrentConversationSlice.actions;
