import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { sendRpcRequest } from "../../services/apiClient";

interface MessengerHistoryState {
  messengerHistories: any[];
  loading: boolean;
  error: string | null;
}

const initialState: MessengerHistoryState = {
  messengerHistories: [],
  loading: false,
  error: null,
};

export const fetchMessengerHistory = createAsyncThunk(
  "messengerHistory/fetchMessengerHistory",
  async (
    {
      deviceId,
      dateFrom,
      dateTo,
      messengerId,
      recStart,
    }: {
      deviceId: string;
      dateFrom: Date;
      dateTo: Date;
      messengerId: number;
      recStart: number;
    },
    { rejectWithValue }
  ) => {
    try {
      const response = await sendRpcRequest<any[]>("data.getcontent", {
        deviceId,
        type: messengerId,
        dateFrom,
        dateTo,
        recStart: recStart,
        recLimit: 500,
      });

      return response;
    } catch (error: unknown) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue(error.message);
      }

      return rejectWithValue("Unknown error occurred");
    }
  }
);

const messengerHistorySlice = createSlice({
  name: "messengerHistory",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchMessengerHistory.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchMessengerHistory.fulfilled, (state, action) => {
        state.loading = false;
        state.messengerHistories = action.payload;
      })
      .addCase(fetchMessengerHistory.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export default messengerHistorySlice.reducer;
