import { getCookie } from "@insite/client-framework/Common/Cookies";
import { createHandlerChainRunnerOptionalParameter, Handler } from "@insite/client-framework/HandlerCreator";
import { API_URL_CURRENT_FRAGMENT } from "@insite/client-framework/Services/ApiService";
import { clearCart, ClearCartApiParameter, removeCartLines } from "@insite/client-framework/Services/CartService";
import loadCurrentCart from "@insite/client-framework/Store/Data/Carts/Handlers/LoadCurrentCart";
// eslint-disable-next-line spire/fenced-imports
import { NavigationModeCookieName } from "@insite/content-library/Components/NavigationModeMenu";

type HandlerType = Handler<
    {
        /**
         * @deprecated this is not supported. It is here to prevent build errors because previously it could be passed in without causing a failure.
         */
        cartId?: string;
    },
    {
        apiParameter: ClearCartApiParameter;
    }
>;

export const DispatchBeginRemoveCart: HandlerType = props => {
    props.dispatch({
        type: "Context/BeginUpdatingCart",
    });
    props.dispatch({
        type: "Pages/Cart/BeginClearCart",
    });
};

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

export const CallClearCart: HandlerType = async props => {
    const currentMode = getCookie(NavigationModeCookieName);
    if (currentMode === "Vmi") {
        await removeCartLines({ ...props.apiParameter });
    } else {
        await clearCart(props.apiParameter);
    }
};

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

export const LoadCart: HandlerType = props => {
    props.dispatch(
        loadCurrentCart({
            getPromotions: true,
            onSuccess: () => {
                props.dispatch({
                    type: "Context/CompleteUpdatingCart",
                });
                props.dispatch({
                    type: "Pages/Cart/CompleteClearCart",
                });
            },
        }),
    );
};

/** @deprecated Not needed anymore */
export const LoadPromotions: HandlerType = () => {};

export const chain = [
    DispatchBeginRemoveCart,
    PopulateApiParameter,
    CallClearCart,
    ResetData,
    LoadCart,
    LoadPromotions,
];

const clearCurrentCart = createHandlerChainRunnerOptionalParameter(chain, {}, "ClearCurrentCart");
export default clearCurrentCart;
