import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { sendRemoveFromCartEvent } from "@insite/client-framework/OdpEvents/UpdateCartEvents";
import { API_URL_CURRENT_FRAGMENT } from "@insite/client-framework/Services/ApiService";
import {
    getCartLine,
    RemoveCartLineApiParameter,
    removeCartLineWithResult as removeCartLineApi,
} from "@insite/client-framework/Services/CartService";
import { getCurrentCartState } from "@insite/client-framework/Store/Data/Carts/CartsSelector";
import loadCurrentCart from "@insite/client-framework/Store/Data/Carts/Handlers/LoadCurrentCart";

type Parameter = {
    cartLineId: string;
};

type Props = {
    apiParameter: RemoveCartLineApiParameter;
};

type HandlerType = Handler<Parameter, Props>;

export const DispatchBeginRemoveCartLine: HandlerType = props => {
    props.dispatch({
        type: "Context/BeginUpdatingCart",
    });
    props.dispatch({
        type: "Pages/Cart/BeginRemoveCartLine",
        cartLineId: props.parameter.cartLineId,
    });
};

export const SendRemoveFromCartEvent: HandlerType = props => {
    const state = props.getState();

    const cartLines = getCurrentCartState(state).value?.cartLines;
    if (!cartLines) return;

    const { cartLineId } = props.parameter;

    const line = cartLines.find(({ id }) => id === cartLineId);

    if (!line) return;

    const { productId, qtyOrdered } = line;

    if (!productId || !qtyOrdered) return;

    sendRemoveFromCartEvent({ productId, qtyOrdered }, state);
};

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

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

export const LoadCart: HandlerType = props => {
    props.dispatch(loadCurrentCart({ getPromotions: true }));
};

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

export const DispatchCompleteRemoveCartLine: HandlerType = props => {
    props.dispatch({
        type: "Pages/Cart/CompleteRemoveCartLine",
        cartLineId: props.parameter.cartLineId,
    });
    props.dispatch({
        type: "Context/CompleteUpdatingCart",
    });
    props.dispatch({
        type: "Data/OrderApprovals/Reset",
    });
};

export const chain = [
    DispatchBeginRemoveCartLine,
    SendRemoveFromCartEvent,
    PopulateApiParameter,
    RemoveCartLine,
    LoadCart,
    LoadPromotions,
    DispatchCompleteRemoveCartLine,
];

const removeCartLine = createHandlerChainRunner(chain, "RemoveCartLine");
export default removeCartLine;
