import isApiError from "@insite/client-framework/Common/isApiError";
import { createHandlerChainRunner, HandlerWithResult } from "@insite/client-framework/HandlerCreator";
import {
    addWishListTags as addWishListTagsApi,
    AddWishListTagsApiParameter,
} from "@insite/client-framework/Services/WishListService";

export interface UpdateWishListResult {
    errorMessage?: string;
}

type HandlerType = HandlerWithResult<AddWishListTagsApiParameter, UpdateWishListResult>;

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

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

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

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

export const chain = [DispatchBeginAddingWishListTags, CallAddWishListTagsApi, DispatchCompleteAddingWishListTags];

const addWishListTags = createHandlerChainRunner(chain, "AddWishListTags");
export default addWishListTags;
