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";
import translate from "@insite/client-framework/Translate";

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

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

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

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

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

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

export const chain = [PrepareData, CallPrepareTrack];

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