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

interface IUsageLimitState {
  days: number[];
  isLoadingDays: boolean;
  errorDays: string | null;
}

const initialState: IUsageLimitState = {
  days: [],
  isLoadingDays: false,
  errorDays: null,
};

export const fetchTimeLimits = createAsyncThunk(
  "timeLimits/fetchTimeLimits",
  async (deviceId: string, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest<{ days: number[] }>(
        "apps.timelimitget",
        {
          deviceId,
        }
      );

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

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

const usageLimitSlice = createSlice({
  name: "usageLimit",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchTimeLimits.pending, (state) => {
        state.isLoadingDays = true;
        state.errorDays = null;
      })
      .addCase(fetchTimeLimits.fulfilled, (state, action) => {
        state.isLoadingDays = false;
        state.days = action.payload;
      })
      .addCase(fetchTimeLimits.rejected, (state, action) => {
        state.isLoadingDays = false;
        state.errorDays = action.payload as string;
      });
  },
});

export default usageLimitSlice.reducer;
