import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    HasOnSuccess,
    makeHandlerChainAwaitable,
} from "@insite/client-framework/HandlerCreator";
import { Cart, CartResult, updateCart, UpdateCartApiParameter } from "@insite/client-framework/Services/CartService";
import loadCart from "@insite/client-framework/Store/Data/Carts/Handlers/LoadCart";
import loadCurrentCart from "@insite/client-framework/Store/Data/Carts/Handlers/LoadCurrentCart";

type HandlerType = ApiHandlerDiscreteParameter<
    {
        cart: Cart;
        fulfillmentMethod: "Ship" | "PickUp";
    } & HasOnSuccess<void>,
    UpdateCartApiParameter,
    CartResult
>;

export const PopulateApiParameter: HandlerType = props => {
    props.apiParameter = {
        cart: {
            ...props.parameter.cart,
            fulfillmentMethod: props.parameter.fulfillmentMethod,
        },
    };
};

export const UpdateCart: HandlerType = async props => {
    props.apiResult = await updateCart(props.apiParameter);
};

export const LoadCart: HandlerType = async props => {
    if (props.parameter.cart.isAwaitingApproval) {
        if (props.parameter.onSuccess) {
            // if we want to wait until the operation is complete, the cart must first be loaded
            const awaitableLoadCurrentCart = makeHandlerChainAwaitable(loadCurrentCart);
            await awaitableLoadCurrentCart({ getPromotions: true })(props.dispatch, props.getState);
        } else {
            props.dispatch(loadCurrentCart({ getPromotions: true }));
        }

        return;
    }

    if (props.parameter.onSuccess) {
        // if we want to wait until the operation is complete, the cart must first be loaded
        const awaitableLoadCart = makeHandlerChainAwaitable(loadCart);
        await awaitableLoadCart({ cartId: props.parameter.cart.id, getPromotions: true } as any)(
            props.dispatch,
            props.getState,
        );
    } else {
        props.dispatch(loadCart({ cartId: props.parameter.cart.id, getPromotions: true }));
    }
};

export const ExecuteOnSuccessCallback: HandlerType = props => {
    props.parameter.onSuccess?.();
};

export const chain = [PopulateApiParameter, UpdateCart, LoadCart, ExecuteOnSuccessCallback];

const setFulfillmentMethod = createHandlerChainRunner(chain, "SetFulfillmentMethod");
export default setFulfillmentMethod;
