import { createSlice } from '@reduxjs/toolkit';
import { sendMessage } from '../api/api';

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

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

const sendMessageSlice = createSlice({
  name: 'sendMessage',
  initialState,
  reducers: {
    resetSendMessageState: (state) => {
      state.loading = false;
      state.success = false;
      state.error = null;
      state.messageData = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(sendMessage.pending, (state) => {
        state.loading = true;
        state.success = false;
        state.error = null;
      })
      .addCase(sendMessage.fulfilled, (state, action) => {
        state.loading = false;
        state.success = true;
        state.messageData = action.payload;
      })
      .addCase(sendMessage.rejected, (state, action) => {
        state.loading = false;
        state.success = false;
        state.error = action.payload as string;
      });
  },
});

export const { resetSendMessageState } = sendMessageSlice.actions;

export default sendMessageSlice.reducer;
