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

type HandlerType = Handler<
    {
        products: ProductModel[];
        pagination?: Readonly<PaginationModel>;
        attributeTypeFacets?: AttributeTypeFacetModel[] | null;
        originalQuery?: string;
    },
    { recommendation: ProductRecommendationSearchResultsModel }
>;

export const PrepareData: HandlerType = props => {
    const {
        getState,
        parameter: { products, pagination, attributeTypeFacets, originalQuery },
    } = props;

    if (!pagination) {
        return false;
    }

    const filters =
        attributeTypeFacets?.map(o => ({
            filter: o.name,
            operator: "IN",
            values: o.attributeValueFacets?.filter(p => p.selected).map(p => p.value),
        })) || [];

    const topResults = products.slice(0, 3).map(o => ({ refCode: o.id })) || [];

    props.recommendation = {
        type: "searchresults",
        searchResults: {
            term: originalQuery || "",
            totalNumberOfResults: pagination.totalItemCount,
            pageNumber: pagination.currentPage,
            resultsOnPage: pagination.pageSize,
            filters,
            topResults,
        },
        ...generateGeneralPrepare(getState()),
    };
};

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

export const chain = [PrepareData, CallPrepareTrack];

const prepareSearchResultPage = createHandlerChainRunner(chain, "PrepareSearchResultPage");
export default prepareSearchResultPage;
