import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import prepareCheckout from "@insite/client-framework/Store/Components/ProductRecommendations/Handlers/PrepareCheckout";
import { getCartState, getCurrentCartState } from "@insite/client-framework/Store/Data/Carts/CartsSelector";

type HandlerType = Handler<{
    cartId?: string;
}>;

export const DispatchSetProductRecsCalled: HandlerType = props => {
    props.dispatch({
        type: "Pages/CheckoutReviewAndSubmit/SetProductRecsCalled",
    });
};

export const PrepareCheckout: HandlerType = ({ getState, dispatch, parameter: { cartId } }) => {
    const state = getState();
    const cartState = cartId ? getCartState(state, cartId) : getCurrentCartState(state);
    if (cartState.value) {
        dispatch(prepareCheckout({ cart: cartState.value }));
    }
};

export const chain = [DispatchSetProductRecsCalled, PrepareCheckout];

const notifyProductRecs = createHandlerChainRunner(chain, "NotifyProductRecs");
export default notifyProductRecs;
