import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { SpecialProductState } from "../../../features/view/public/productListPage/productlistingTypes";
import { getSpecialProductList } from "./specialProductAPI";

const initialState: SpecialProductState = {
  specialProductsList: { data: [], loader: false },
};

export const getSpecialProductListAsync = createAsyncThunk(
  "productList/special-list",
  async () => {
    const response = await getSpecialProductList();
    return response;
  }
);

export const specialProductSlice = createSlice({
  name: "specialProductList",
  initialState,
  reducers: {},

  extraReducers: (builder) => {
    builder
      .addCase(getSpecialProductListAsync.pending, (state) => {
        state.specialProductsList.loader = true;
      })
      .addCase(getSpecialProductListAsync.fulfilled, (state, action: any) => {
        state.specialProductsList.loader = false;
        // state.specialProductsList.data = action?.payload?.data || [];

        const data = action?.payload?.data?.data || [];
        const filteredProducts = data?.map((item: any) => {
          return {
            ...item,
            products: item?.products?.filter((product: any) => {
              // Check if there is at least one SKU with status "Visible"
              return product?.skus?.some(
                (sku: { sku_status: string }) => sku?.sku_status === "Visible"
              );
            }),
          };
        });

        state.specialProductsList.data = filteredProducts || [];
      })
      .addCase(getSpecialProductListAsync.rejected, (state) => {
        state.specialProductsList.loader = false;
      });
  },
});

export default specialProductSlice.reducer;
