import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { Cart } from "@insite/client-framework/Services/CartService";
import { ProductRecommendationOrderModel } 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";

type HandlerType = Handler<{ cart: Cart }, { recommendation: ProductRecommendationOrderModel }>;

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.erpNumber,
            qty: o.qtyOrdered,
            price: o.pricing?.actualPrice,
        })) || [];

    props.recommendation = {
        type: "order",
        order: {
            orderNo: cart.erpOrderNumber || cart.orderNumber,
            items: cartItems,
            shipping: cart.shippingAndHandling,
            total: cart.orderGrandTotal,
            subtotal: cart.orderSubTotal,
            currency,
        },
        ...generateGeneralPrepare(getState()),
    };
};

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

export const chain = [PrepareData, CallPrepareTrack];

const prepareOrder = createHandlerChainRunner(chain, "PrepareOrder");
export default prepareOrder;
