import { createSelector } from '@reduxjs/toolkit';
import { stateKey } from '../../../app/state-key.js';
import { commerceCategoryFacetSearchSetReducer as categoryFacetSearchSet } from '../../../features/commerce/facets/facet-search-set/category/commerce-category-facet-search-set-slice.js';
import { getFacetIdWithCommerceFieldSuggestionNamespace } from '../../../features/commerce/facets/facet-search-set/commerce-facet-search-actions.js';
import { commerceFacetSetReducer as commerceFacetSet } from '../../../features/commerce/facets/facet-set/facet-set-slice.js';
import { fieldSuggestionsOrderReducer as fieldSuggestionsOrder } from '../../../features/commerce/facets/field-suggestions-order/field-suggestions-order-slice.js';
import { selectCategoryFacetSearchResult } from '../../../features/facets/facet-search-set/category/category-facet-search-actions.js';
import { loadReducerError } from '../../../utils/errors.js';
import { buildController, } from '../../controller/headless-controller.js';
import { buildCategoryFacetSearch } from '../core/facets/category/headless-commerce-category-facet-search.js';
/**
 * The `CategoryFieldSuggestions` controller provides query suggestions based on a particular category facet field.
 * @param engine - The headless commerce engine.
 * @param options - The options for the `CategoryFieldSuggestions` controller.
 * @returns A `CategoryFieldSuggestions` controller instance.
 *
 * @group Buildable controllers
 * @category CategoryFieldSuggestions
 */
export function buildCategoryFieldSuggestions(engine, options) {
    if (!loadFieldSuggestionsReducers(engine)) {
        throw loadReducerError;
    }
    const { dispatch } = engine;
    const namespacedFacetId = getFacetIdWithCommerceFieldSuggestionNamespace(options.facetId);
    const facetSearch = buildCategoryFacetSearch(engine, {
        options: {
            facetId: namespacedFacetId,
            ...options.facetSearch,
            numberOfValues: 10,
        },
        select: () => {
            dispatch(options.fetchProductsActionCreator());
        },
        isForFieldSuggestions: false,
    });
    const getState = () => engine[stateKey];
    const getFacetForFieldSuggestions = (facetId) => {
        return getState().fieldSuggestionsOrder.find((facet) => facet.facetId === facetId);
    };
    const controller = buildController(engine);
    const facetSearchStateSelector = createSelector((state) => state.categoryFacetSearchSet[namespacedFacetId], (facetSearch) => ({
        isLoading: facetSearch.isLoading,
        moreValuesAvailable: facetSearch.response.moreValuesAvailable,
        query: facetSearch.options.query,
        values: facetSearch.response.values,
    }));
    return {
        ...controller,
        ...facetSearch,
        select: (value) => {
            dispatch(selectCategoryFacetSearchResult({ facetId: options.facetId, value }));
            dispatch(options.fetchProductsActionCreator());
        },
        updateText: (text) => {
            facetSearch.updateText(text);
            facetSearch.search();
        },
        get state() {
            const facet = getFacetForFieldSuggestions(options.facetId);
            return {
                displayName: facet.displayName,
                field: facet.field,
                facetId: facet.facetId,
                ...facetSearchStateSelector(getState()),
            };
        },
        type: 'hierarchical',
    };
}
function loadFieldSuggestionsReducers(engine) {
    engine.addReducers({
        fieldSuggestionsOrder,
        categoryFacetSearchSet,
        commerceFacetSet,
    });
    return true;
}
