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";
import displayOrder from "@insite/client-framework/Store/Pages/OrderApprovalDetails/Handlers/DisplayOrder";

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

export const PopulateApiParameter: HandlerType = props => {
    props.apiParameter = {
        cart: {
            ...props.parameter.cart,
            orderApprovalStatus: "RevisionRequested",
            requestRevisionMessage: props.parameter.requestRevisionMessage,
        },
    };
};

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

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

export const DisplayOrder: HandlerType = props => {
    props.dispatch(displayOrder({ cartId: props.parameter.cart.id }));
};

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

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

const requestRevision = createHandlerChainRunner(chain, "RequestRevision");
export default requestRevision;
