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

interface ICallHistory {
  name: string;
  call_type: string;
  date: string;
}

interface CallHistoryState {
  callHistories: ICallHistory[];
  loading: boolean;
  error: string | null;
}

const initialState: CallHistoryState = {
  callHistories: [],
  loading: false,
  error: null,
};

export const fetchCallHistory = createAsyncThunk(
  "callHistory/fetchCallHistory",
  async (
    {
      deviceId,
      dateFrom,
      dateTo,
      recStart,
    }: { deviceId: string; dateFrom: Date; dateTo: Date; recStart: number },
    { rejectWithValue }
  ) => {
    try {
      const response = await sendRpcRequest<{ list: ICallHistory[] }>(
        "data.getcontent",
        {
          deviceId,
          type: 3,
          dateFrom,
          dateTo,
          recStart,
          recLimit: 50,
        }
      );

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

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

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

export default callHistorySlice.reducer;
