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

interface IBrowserHistory {
  name: string;
  duration: string;
  date: string;
}

interface IBrowserHistoryState {
  browserHistories: IBrowserHistory[];
  loading: boolean;
  error: string | null;
}

const initialState: IBrowserHistoryState = {
  browserHistories: [],
  loading: false,
  error: null,
};

export const fetchBrowserHistory = createAsyncThunk(
  "browserHistory/fetchBrowserHistory",
  async (
    {
      deviceId,
      dateFrom,
      dateTo,
      recStart,
    }: { deviceId: string; dateFrom: Date; dateTo: Date; recStart: number },
    { rejectWithValue }
  ) => {
    try {
      const response = await sendRpcRequest<{ list: IBrowserHistory[] }>(
        "data.getcontent",
        {
          deviceId,
          type: 38,
          dateFrom,
          dateTo,
          recStart: 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 browserHistorySlice = createSlice({
  name: "browserHistory",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchBrowserHistory.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchBrowserHistory.fulfilled, (state, action) => {
        state.loading = false;
        state.browserHistories = action.payload;
      })
      .addCase(fetchBrowserHistory.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export default browserHistorySlice.reducer;
