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

interface IRouteHistory {
  date: string;
  location: {
    lat: string;
    lon: string;
  };
}

interface IDataState {
  routeHistory: IRouteHistory[];
  isRouteHistoryLoading: boolean;
  routeHistoryError: string | null;
}

const initialState: IDataState = {
  routeHistory: [],
  isRouteHistoryLoading: false,
  routeHistoryError: null,
};

export const getRouteHistory = createAsyncThunk(
  "data/getRouteHistory",
  async (
    {
      deviceId,
      dateFrom,
      dateTo,
      recStart = 0,
      recLimit = 1000,
    }: {
      deviceId: string;
      dateFrom: Date;
      dateTo: Date;
      recStart?: number;
      recLimit?: number;
    },
    { rejectWithValue }
  ) => {
    try {
      const response = await sendRpcRequest<{ list: IRouteHistory[] }>(
        "data.getroutehistory",
        {
          deviceId,
          dateFrom,
          dateTo,
          recStart,
          recLimit,
        }
      );

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

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

const dataSlice = createSlice({
  name: "data",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getRouteHistory.pending, (state) => {
        state.isRouteHistoryLoading = true;
        state.routeHistoryError = null;
      })
      .addCase(getRouteHistory.fulfilled, (state, action) => {
        state.isRouteHistoryLoading = false;
        state.routeHistory = action.payload;
      })
      .addCase(getRouteHistory.rejected, (state, action) => {
        state.isRouteHistoryLoading = false;
        state.routeHistoryError = action.payload as string;
      });
  },
});

export default dataSlice.reducer;
