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

interface MessengerHistoryState {
  chats: IChat[];
  loading: boolean;
  error: string | null;
}

const initialState: MessengerHistoryState = {
  chats: [],
  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<{ chats: IChat[] }>(
        "data.getcontent",
        {
          deviceId,
          type: messengerId,
          dateFrom,
          dateTo,
          recStart: recStart,
          recLimit: 500,
        }
      );

      return response.chats;
    } 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.chats = action.payload;
      })
      .addCase(fetchMessengerHistory.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export default messengerHistorySlice.reducer;
