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

interface MessageState {
  loading: boolean;
  messageData: any | null;
  error: string | null;
}

const initialState: MessageState = {
  loading: false,
  messageData: null,
  error: null,
};

const messageSlice = createSlice({
  name: "messages",
  initialState,
  reducers: {
    // Add additional reducers if needed
  },
  extraReducers: (builder) => {
    builder
      .addCase(message.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(message.fulfilled, (state, action: PayloadAction<any>) => {
        state.loading = false;

      //   // Replace the conversations array directly
        state.messageData = {
          ...action?.payload,
          data: {
            ...action?.payload.data,
            conversations: action?.payload?.data?.conversations || [],
          },
        };
      })

      .addCase(message.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || "Failed to fetch messages";
      });
  },
});

export default messageSlice.reducer;
