import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import API from "../../api";

const baseURL = process.env.NEXT_PUBLIC_BASE_URL_RETAILER;

export const getCategories = createAsyncThunk(
  "get/categories",
  async (_, thunkAPI) => {
    try {
      const response: any = await API.get(
        `${baseURL}/quotation/get_category_dp`
      );
      if (response.data === undefined || typeof response.data !== "object") {
        return thunkAPI.rejectWithValue("Invalid data received");
      }
      console.log(response, "api resp >>>>>")
      return response?.data;
    } catch (error: any) {
      const message =
        (error.response && error.response.data && error.response.data?.message) ||
        error.message ||
        error.toString();
      return thunkAPI.rejectWithValue(message);
    }
  }
);

interface categoryState {
  isGetCategorySuccess: boolean;
  categoryData: any | null;
  isGetCategoryError: string | undefined;
  isGetCategoryLoading: boolean;
}

const initialState: categoryState = {
  isGetCategorySuccess: false,
  categoryData: null,
  isGetCategoryError: "",
  isGetCategoryLoading: false
};

const categorySlice = createSlice({
  name: "categorySlice",
  initialState,
  reducers: {
    resetGetCategory: (state: categoryState) => {
      state.isGetCategorySuccess = false;
      state.categoryData = null;
      state.isGetCategoryError = "";
      state.isGetCategoryLoading = false;
    }
  },
  extraReducers: (builder) => {
    builder
      .addCase(getCategories.pending, (state: categoryState) => {
        state.isGetCategoryLoading = true;
        state.isGetCategoryError = "";
        state.categoryData = null;
        state.isGetCategorySuccess = false;
      })
      .addCase(
        getCategories.fulfilled,
        (state: categoryState, action: ReturnType<typeof getCategories.fulfilled>) => {
          state.isGetCategoryLoading = false;
          state.categoryData = action?.payload?.categoryData;
          state.isGetCategorySuccess = true;
          state.isGetCategoryError = "";
        }
      )
      .addCase(getCategories.rejected, (state: categoryState, action: any) => {
        state.isGetCategoryLoading = false;
        state.isGetCategoryError = action?.payload || "An error occurred";
        state.isGetCategorySuccess = false;
        state.categoryData = null; // Reset data in case of rejection
      })
  },
});

export const { resetGetCategory } = categorySlice.actions;

export default categorySlice.reducer;

