import {
    createHandlerChainRunner,
    Handler,
    markSkipOnCompleteIfOnSuccessIsSet,
} from "@insite/client-framework/HandlerCreator";
import { API_URL_CURRENT_FRAGMENT } from "@insite/client-framework/Services/ApiService";
import {
    addCart,
    AddCartApiParameter,
    Cart,
    getCart,
    GetCartApiParameter,
} from "@insite/client-framework/Services/CartService";
import addCartLineCollectionFromVmiBins from "@insite/client-framework/Store/Pages/OrderUpload/Handlers/AddCartLineCollectionFromVmiBins";
import setCartRequestInProcess from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetCartRequestInProcess";
import { VmiBinModel } from "@insite/client-framework/Types/ApiModels";

interface Parameter {
    vmiBins: VmiBinModel[];
    vmiLocationId: string;
    showNotification?: (isMultipleProduct: boolean) => void;
    onSuccess?: () => void;
}

interface Props {
    cart?: Cart;
    addAlternateCartSuccessfully?: boolean;
}

type HandlerType = Handler<Parameter, Props>;

export const SetCartRequestInProcess: HandlerType = props => {
    props.dispatch(setCartRequestInProcess({ cartRequestInProcess: true }));
};

export const GetCart: HandlerType = async props => {
    const { cart } = await getCart({ cartId: API_URL_CURRENT_FRAGMENT } as GetCartApiParameter);
    props.cart = cart;
};

export const AddAlternateCart: HandlerType = async props => {
    if (props.cart && props.cart.status !== "AlternateCart") {
        const { successful } = await addCart({ vmiLocationId: props.parameter.vmiLocationId } as AddCartApiParameter);
        props.addAlternateCartSuccessfully = successful;
    }
};

export const GetAlternateCart: HandlerType = async props => {
    if (props.addAlternateCartSuccessfully) {
        const { cart } = await getCart({ cartId: API_URL_CURRENT_FRAGMENT } as GetCartApiParameter);
        props.cart = cart;
    }
};

export const AddCartLineCollectionFromVmiBins: HandlerType = props => {
    if (props.cart) {
        props.dispatch(
            addCartLineCollectionFromVmiBins({
                vmiBins: props.parameter.vmiBins,
                onSuccess: () => {
                    props.parameter.showNotification?.(props.parameter.vmiBins.length > 1);
                },
            }),
        );
    }
};

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

export const chain = [
    SetCartRequestInProcess,
    GetCart,
    AddAlternateCart,
    GetAlternateCart,
    AddCartLineCollectionFromVmiBins,
    ExecuteOnSuccessCallback,
];

const updateCart = createHandlerChainRunner(chain, "UpdateCart");
export default updateCart;
