import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { ProductRecommendationBrandModel } 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 { FacetModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = Handler<{ brandFacets: FacetModel[] }, { recommendation: ProductRecommendationBrandModel }>;

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

    const selectedBrand = brandFacets.find(o => o.selected);
    if (!selectedBrand) {
        return false;
    }

    props.recommendation = {
        type: "brand",
        brand: selectedBrand.name,
        ...generateGeneralPrepare(getState()),
    };
};

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

export const chain = [PrepareData, CallPrepareTrack];

const prepareBrand = createHandlerChainRunner(chain, "PrepareBrand");
export default prepareBrand;
