import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { ProductRecommendationBasketModel } 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 { getSession } from "@insite/client-framework/Store/Context/ContextSelectors";
import { CartModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = Handler<{ cart: CartModel }, { recommendation: ProductRecommendationBasketModel }>;

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

    const session = getSession(getState());
    const currency = session?.currency?.currencyCode || "";

    const cartItems =
        cart.cartLines?.map(o => ({
            refCode: o.parentProductErpNumber || o.erpNumber,
            qty: o.qtyOrdered,
            price: o.pricing?.actualPrice,
        })) || [];

    props.recommendation = {
        type: "basket",
        basket: {
            basketId: cart.trackId,
            items: cartItems,
            currency,
        },
        ...generateGeneralPrepare(getState()),
    };
};

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

export const chain = [PrepareData, CallPrepareTrack];

const prepareCart = createHandlerChainRunner(chain, "PrepareCart");
export default prepareCart;
