import { createSelector } from '@reduxjs/toolkit';
import { stateKey } from '../../../../../app/state-key.js';
import { clearAllCoreFacets } from '../../../../../features/commerce/facets/core-facet/core-facet-actions.js';
import { commerceFacetOrderReducer as facetOrder } from '../../../../../features/commerce/facets/facet-order/commerce-facet-order-slice.js';
import { commerceFacetSetReducer as commerceFacetSet } from '../../../../../features/commerce/facets/facet-set/facet-set-slice.js';
import { loadReducerError } from '../../../../../utils/errors.js';
import { buildController, } from '../../../../controller/headless-controller.js';
/**
 * @internal
 *
 * Creates a `FacetGenerator` sub-controller.
 *
 * @param engine - The commerce engine.
 * @param options - The facet generator options used internally.
 * @returns A `FacetGenerator` sub-controller.
 */
export function buildFacetGenerator(engine, options) {
    if (!loadCommerceFacetGeneratorReducers(engine)) {
        throw loadReducerError;
    }
    const controller = buildController(engine);
    const { dispatch } = engine;
    const createFacetControllers = createSelector([
        (state) => state.facetOrder,
        (state) => state.commerceFacetSet,
    ], (facetOrder, commerceFacetSet) => facetOrder.map((facetId) => createFacetController(commerceFacetSet, facetId)));
    const createFacetController = createSelector((commerceFacetSet, facetId) => ({
        facetId,
        type: commerceFacetSet[facetId].request.type,
    }), ({ type, facetId }) => {
        switch (type) {
            case 'dateRange':
                return options.buildDateFacet(engine, { facetId });
            case 'hierarchical':
                return options.buildCategoryFacet(engine, { facetId });
            case 'numericalRange':
                return options.buildNumericFacet(engine, { facetId });
            case 'regular':
                return options.buildRegularFacet(engine, { facetId });
            case 'location':
                return options.buildLocationFacet(engine, { facetId });
        }
    });
    return {
        ...controller,
        deselectAll: () => {
            dispatch(clearAllCoreFacets());
            dispatch(options.fetchProductsActionCreator());
        },
        get facets() {
            return createFacetControllers(engine[stateKey]);
        },
        get state() {
            return engine[stateKey].facetOrder;
        },
    };
}
function loadCommerceFacetGeneratorReducers(engine) {
    engine.addReducers({ facetOrder, commerceFacetSet });
    return true;
}
