import { isGuid } from "@insite/client-framework/Common/StringHelpers";
import {
    ApiHandlerDiscreteParameter,
    createHandlerChainRunner,
    HasOnError,
} from "@insite/client-framework/HandlerCreator";
import { API_URL_CURRENT_FRAGMENT } from "@insite/client-framework/Services/ApiService";
import { GetCartApiParameter } from "@insite/client-framework/Services/CartService";
import { getCartState } from "@insite/client-framework/Store/Data/Carts/CartsSelector";
import loadCart from "@insite/client-framework/Store/Data/Carts/Handlers/LoadCart";
import { CartModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = ApiHandlerDiscreteParameter<
    {
        cartId: string;
    } & HasOnError,
    GetCartApiParameter,
    CartModel
>;

export const PopulateApiParameter: HandlerType = props => {
    const state = props.getState();
    const currentCartId = state.pages.savedOrderDetails.cartId;
    const savedOrderState = getCartState(state, props.parameter.cartId);
    if (savedOrderState.value?.cartLines && savedOrderState.value.cartLines.length > 0) {
        return;
    }

    if (currentCartId === props.parameter.cartId) {
        if (!savedOrderState.isLoading) {
            props.parameter.onError?.();
        }

        return false;
    }

    if (props.parameter.cartId !== API_URL_CURRENT_FRAGMENT && !isGuid(props.parameter.cartId)) {
        props.parameter.onError?.();
        return false;
    }

    props.apiParameter = {
        cartId: props.parameter.cartId,
        expand: ["cartLines", "hiddenproducts", "restrictions"],
    } as GetCartApiParameter;
};

export const DispatchSetCartId: HandlerType = props => {
    props.dispatch({
        type: "Pages/SavedOrderDetails/SetCartId",
        cartId: props.parameter.cartId,
    });
};

export const DispatchLoadOrderIfNeeded: HandlerType = props => {
    if (props.apiParameter) {
        props.dispatch(
            loadCart({
                apiParameter: props.apiParameter,
            }),
        );
    }
};

export const chain = [PopulateApiParameter, DispatchSetCartId, DispatchLoadOrderIfNeeded];

const displayOrder = createHandlerChainRunner(chain, "DisplayOrder");
export default displayOrder;
