import { createHandlerChainRunner, Handler } from "@insite/client-framework/HandlerCreator";
import { CatalogPage } from "@insite/client-framework/Services/CategoryService";
import prepareBrand from "@insite/client-framework/Store/Components/ProductRecommendations/Handlers/PrepareBrand";
import prepareCategory from "@insite/client-framework/Store/Components/ProductRecommendations/Handlers/PrepareCategory";
import prepareSearchResultPage from "@insite/client-framework/Store/Components/ProductRecommendations/Handlers/PrepareSearchResultPage";
import { getProductListDataViewProperty } from "@insite/client-framework/Store/Pages/ProductList/ProductListSelectors";
import { ProductModel } from "@insite/client-framework/Types/ApiModels";

type HandlerType = Handler<Parameter>;

interface Parameter {
    isSearch: boolean;
    catalogPage: CatalogPage | undefined;
    products: ProductModel[] | undefined;
}

export const PrepareProductRecs: HandlerType = ({
    getState,
    dispatch,
    parameter: { isSearch, catalogPage, products },
}) => {
    const state = getState();

    if (catalogPage && !isSearch && !catalogPage.brandId) {
        const pagination = getProductListDataViewProperty(state, "pagination");
        dispatch(prepareCategory({ catalogPage, pageNumber: pagination?.currentPage }));
    }

    if (products) {
        if (isSearch) {
            const pagination = getProductListDataViewProperty(state, "pagination");
            const attributeTypeFacets = getProductListDataViewProperty(state, "attributeTypeFacets");
            const originalQuery = getProductListDataViewProperty(state, "originalQuery");
            dispatch(prepareSearchResultPage({ products, pagination, attributeTypeFacets, originalQuery }));
        } else if (catalogPage && !isSearch && catalogPage.brandId) {
            const brandFacets = getProductListDataViewProperty(state, "brandFacets");
            if (brandFacets) {
                dispatch(prepareBrand({ brandFacets }));
            }
        }
    }
};

export const chain = [PrepareProductRecs];

const prepareProductRecs = createHandlerChainRunner(chain, "PrepareProductRecs");
export default prepareProductRecs;
