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

interface INotification {
  id: string;
  caption: string;
  text: string;
  action: string;
  date: string;
  deviceId: string;
  type: string;
}

interface INotificationState {
  notifications: INotification[];
  loading: boolean;
}

const initialState: INotificationState = {
  notifications: [],
  loading: false,
};

export const getList = createAsyncThunk(
  "notifications/fetch",
  async (
    { dateFrom, dateTo }: { dateFrom: Date; dateTo: Date },
    { rejectWithValue }
  ) => {
    try {
      const response = await sendRpcRequest<{ list: INotification[] }>(
        "notif.getList",
        {
          dateFrom,
          dateTo,
          recStart: 0,
          recLimit: 30,
        }
      );

      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 notificationSlice = createSlice({
  name: "notifications",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getList.pending, (state) => {
        state.loading = true;
      })
      .addCase(getList.fulfilled, (state, action) => {
        state.loading = false;
        state.notifications = action.payload;
      })
      .addCase(getList.rejected, (state) => {
        state.loading = false;
      });
  },
});

export default notificationSlice.reducer;
