import { stateKey } from '../../../../app/state-key.js';
import { didYouMeanReducer as didYouMean } from '../../../../features/commerce/did-you-mean/did-you-mean-slice.js';
import { updateQuery } from '../../../../features/commerce/query/query-actions.js';
import { executeSearch } from '../../../../features/commerce/search/search-actions.js';
import { loadReducerError } from '../../../../utils/errors.js';
import { buildController, } from '../../../controller/headless-controller.js';
/**
 * The `DidYouMean` controller is responsible for handling query corrections.
 *
 * @param engine - The commerce engine.
 * @param options - The configurable `DidYouMean` options.
 * @returns A `DidYouMean` controller.
 *
 * @group Sub-controllers
 * @category DidYouMean
 */
export function buildDidYouMean(engine, options = {}) {
    if (!loadDidYouMeanReducers(engine)) {
        throw loadReducerError;
    }
    const { enableResults = false } = options;
    const controller = buildController(engine);
    const getState = () => engine[stateKey].didYouMean;
    return {
        ...controller,
        applyCorrection() {
            engine.dispatch(updateQuery({ query: this.state.queryCorrection.correctedQuery }));
            engine.dispatch(executeSearch({ enableResults }));
        },
        get state() {
            const state = getState();
            return {
                originalQuery: state.originalQuery,
                wasCorrectedTo: state.wasCorrectedTo,
                queryCorrection: state.queryCorrection,
                hasQueryCorrection: state.queryCorrection.correctedQuery !== '',
                wasAutomaticallyCorrected: state.wasCorrectedTo !== '',
            };
        },
    };
}
function loadDidYouMeanReducers(engine) {
    engine.addReducers({
        didYouMean,
    });
    return true;
}
