import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { ProductRecommendationWishlistModel } from "@insite/client-framework/Services/ProductRecommendationsService";
import prepareTrack from "@insite/client-framework/Store/Components/ProductRecommendations/Handlers/PrepareTrack";
import { generateGeneralPrepare } from "@insite/client-framework/Store/Components/ProductRecommendations/ProductRecommendationsSelector";
import { WishListLineCollectionModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = Handler<
    { wishListLineCollection: WishListLineCollectionModel },
    { recommendation: ProductRecommendationWishlistModel }
>;

export const PrepareData: HandlerType = props => {
    const {
        getState,
        parameter: { wishListLineCollection },
    } = props;

    const wishListItems = wishListLineCollection.wishListLines?.map(o => ({ refCode: o.erpNumber })) || [];

    props.recommendation = {
        type: "wishlist",
        wishList: {
            items: wishListItems,
        },
        ...generateGeneralPrepare(getState()),
    };
};

export const CallPrepareTrack: HandlerType = ({ dispatch, recommendation }) => {
    dispatch(prepareTrack({ prepareTrackData: recommendation }));
};

export const chain = [PrepareData, CallPrepareTrack];

const prepareWishlist = createHandlerChainRunner(chain, "PrepareWishlist");
export default prepareWishlist;
