import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { CatalogPage } from "@insite/client-framework/Services/CategoryService";
import { ProductRecommendationCategoryModel } from "@insite/client-framework/Services/ProductRecommendationsService";
import prepareTrack from "@insite/client-framework/Store/Components/ProductRecommendations/Handlers/PrepareTrack";
import { generateGeneralPrepare } from "@insite/client-framework/Store/Components/ProductRecommendations/ProductRecommendationsSelector";

type HandlerType = Handler<{ catalogPage: CatalogPage }, { recommendation: ProductRecommendationCategoryModel }>;

export const PrepareData: HandlerType = props => {
    const {
        getState,
        parameter: { catalogPage },
    } = props;

    let category = "";
    catalogPage.breadCrumbs?.forEach((item, index) => {
        // We don't need to add "home" to category path
        if (item.text.toLowerCase() === "home") {
            return;
        }

        category += item.text;
        if (catalogPage.breadCrumbs && index !== catalogPage.breadCrumbs.length - 1) {
            category += ">";
        }
    });

    props.recommendation = {
        type: "category",
        category,
        ...generateGeneralPrepare(getState()),
    };
};

export const CallPrepareTrack: HandlerType = ({ dispatch, recommendation }) => {
    dispatch(prepareTrack({ prepareTrackData: recommendation }));
};

export const chain = [PrepareData, CallPrepareTrack];

const prepareCategory = createHandlerChainRunner(chain, "PrepareCategory");
export default prepareCategory;
