import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    HasOnSuccess,
} from "@insite/client-framework/HandlerCreator";
import { ServiceResult } from "@insite/client-framework/Services/ApiService";
import { RemoveCartApiParameter } from "@insite/client-framework/Services/CartService";
import { removeCart as removeCartApi } from "@insite/client-framework/Services/CartService";
import loadCurrentCart from "@insite/client-framework/Store/Data/Carts/Handlers/LoadCurrentCart";

type HandlerType = ApiHandlerDiscreteParameter<
    {
        cartId: string;
        isAlternateCart?: boolean;
    } & HasOnSuccess,
    RemoveCartApiParameter,
    ServiceResult<void>
>;

export const PopulateApiParameter: HandlerType = props => {
    props.apiParameter = {
        cartId: props.parameter.cartId,
        isAlternateCart: props.parameter.isAlternateCart,
    };
};

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

export const LoadCart: HandlerType = props => {
    if (!props.apiParameter?.isAlternateCart) {
        props.dispatch(loadCurrentCart());
    }
};

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

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

const removeCart = createHandlerChainRunner(chain, "RemoveCart");
export default removeCart;
