import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    HasOnSuccess,
} from "@insite/client-framework/HandlerCreator";
import { updateCart, UpdateCartApiParameter } from "@insite/client-framework/Services/CartService";
import { CartModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = ApiHandlerDiscreteParameter<{ cart: CartModel } & HasOnSuccess, UpdateCartApiParameter, CartModel>;

export const PopulateApiParameter: HandlerType = props => {
    props.apiParameter = {
        cart: {
            ...props.parameter.cart,
            orderApprovalStatus: "AwaitingApproval",
            orderApprovalEditResult: "Save",
        },
    };
};

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

export const ResetData: HandlerType = props => {
    props.dispatch({
        type: "Data/OrderApprovals/Reset",
    });
    props.dispatch({
        type: "Data/Carts/Reset",
    });
};

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

export const chain = [PopulateApiParameter, SendDataToApi, ResetData, ExecuteOnSuccessCallback];

const saveOrderApproval = createHandlerChainRunner(chain, "SaveOrderApproval");
export default saveOrderApproval;
