import { ApiHandlerDiscreteParameter, createHandlerChainRunner } from "@insite/client-framework/HandlerCreator";
import { API_URL_CURRENT_FRAGMENT } from "@insite/client-framework/Services/ApiService";
import { AddCartLinesApiParameter, addLineCollection } from "@insite/client-framework/Services/CartService";
import loadCurrentCart from "@insite/client-framework/Store/Data/Carts/Handlers/LoadCurrentCart";
import setCartRequestInProcess from "@insite/client-framework/Store/Pages/VmiBins/Handlers/SetCartRequestInProcess";
import { CartLineCollectionModel, CartLineModel, VmiBinModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = ApiHandlerDiscreteParameter<
    {
        vmiBins: VmiBinModel[];
        onSuccess?: () => void;
    },
    AddCartLinesApiParameter,
    CartLineCollectionModel
>;

export const DispatchBeginAddCartLineCollectionFromVmiBins: HandlerType = props => {
    props.dispatch({
        type: "Context/BeginUpdatingCart",
    });
    props.dispatch({
        type: "Pages/OrderUpload/BeginAddCartLineCollectionFromProducts",
    });
};

export const PopulateApiParameter: HandlerType = props => {
    const cartLineCollection: CartLineModel[] = [];
    props.parameter.vmiBins.forEach(vmiBin => {
        cartLineCollection.push({
            productId: vmiBin.product.id,
            qtyOrdered: vmiBin.product.qtyOrdered,
            unitOfMeasure: vmiBin.product.selectedUnitOfMeasure,
            vmiBinId: vmiBin.id,
        } as CartLineModel);
    });

    cartLineCollection.forEach(line => {
        const parsedQty = line.qtyOrdered ? parseFloat(line.qtyOrdered.toString()) : 1;
        line.qtyOrdered = parsedQty > 0 ? parsedQty : 1;
    });

    props.apiParameter = {
        cartLineCollection: {
            cartLines: cartLineCollection,
        },
        cartId: API_URL_CURRENT_FRAGMENT,
    } as AddCartLinesApiParameter;
};

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

export const LoadCart: HandlerType = props => {
    props.dispatch(
        loadCurrentCart({
            onSuccess: () => {
                props.dispatch(setCartRequestInProcess({ cartRequestInProcess: false }));
            },
        }),
    );
};

export const DispatchCompleteAddCartLineCollectionFromVmiBins: HandlerType = props => {
    props.dispatch({
        type: "Pages/OrderUpload/CompleteAddCartLineCollectionFromProducts",
        result: props.apiResult,
    });
    props.dispatch({
        type: "Context/CompleteUpdatingCart",
    });
};

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

export const chain = [
    DispatchBeginAddCartLineCollectionFromVmiBins,
    PopulateApiParameter,
    SendDataToApi,
    LoadCart,
    DispatchCompleteAddCartLineCollectionFromVmiBins,
    ExecuteOnSuccessCallback,
];

const AddCartLineCollectionFromVmiBins = createHandlerChainRunner(chain, "AddCartLineCollectionFromVmiBins");
export default AddCartLineCollectionFromVmiBins;
