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

interface ICommandState {
  isLoadingBlockDevice: boolean;
  isLoadingUnBlockDevice: boolean;
}

const initialState: ICommandState = {
  isLoadingBlockDevice: false,
  isLoadingUnBlockDevice: false,
};

export const blockDevice = createAsyncThunk(
  "command/blockDevice",
  async (deviceId: string, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest("command.block", {
        deviceId,
        password: "0000",
      });

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

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

export const unBlockDevice = createAsyncThunk(
  "command/unBlockDevice",
  async (deviceId: string, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest("command.block", {
        deviceId,
      });

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

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

const commandSlice = createSlice({
  name: "command",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(blockDevice.pending, (state) => {
        state.isLoadingBlockDevice = true;
      })
      .addCase(blockDevice.fulfilled, (state) => {
        state.isLoadingBlockDevice = false;
      })

      .addCase(unBlockDevice.pending, (state) => {
        state.isLoadingUnBlockDevice = true;
      })
      .addCase(unBlockDevice.fulfilled, (state) => {
        state.isLoadingUnBlockDevice = false;
      });
  },
});

export default commandSlice.reducer;
