import isApiError from "@insite/client-framework/Common/isApiError";
import { createHandlerChainRunner, HandlerWithResult } from "@insite/client-framework/HandlerCreator";
import {
    deleteWishListTags as deleteWishListTagsApi,
    DeleteWishListTagsApiParameter,
} from "@insite/client-framework/Services/WishListService";

export interface UpdateWishListResult {
    errorMessage?: string;
}

type HandlerType = HandlerWithResult<DeleteWishListTagsApiParameter, UpdateWishListResult>;

export const DispatchBeginRemovingWishListTags: HandlerType = props => {
    const wishListId = props.parameter.wishListId;
    if (!wishListId) {
        return false;
    }

    props.result = {};
    props.dispatch({
        type: "Pages/MyListDetails/BeginRemovingWishListTags",
    });
};

export const CallDeleteWishListTagsApi: HandlerType = async props => {
    try {
        await deleteWishListTagsApi(props.parameter);
    } catch (error) {
        if (isApiError(error) && error.status === 400) {
            props.result.errorMessage = error.errorJson.message;
            return;
        }
        throw error;
    }
};

export const DispatchCompleteRemovingWishListTags: HandlerType = props => {
    if (!props.result.errorMessage) {
        props.dispatch({
            type: "Pages/MyListDetails/CompleteRemovingWishListTags",
        });
    }
};

export const chain = [
    DispatchBeginRemovingWishListTags,
    CallDeleteWishListTagsApi,
    DispatchCompleteRemovingWishListTags,
];

const removeWishListTags = createHandlerChainRunner(chain, "RemoveWishListTags");
export default removeWishListTags;
