import { ArrayValue, NumberValue, Schema } from '@coveo/bueno';
import { clearRecentResults, registerRecentResults, } from '../../features/recent-results/recent-results-actions.js';
import { logClearRecentResults } from '../../features/recent-results/recent-results-analytics-actions.js';
import { recentResultsReducer as recentResults } from '../../features/recent-results/recent-results-slice.js';
import { loadReducerError } from '../../utils/errors.js';
import { validateInitialState, validateOptions, } from '../../utils/validate-payload.js';
import { buildController, } from '../controller/headless-controller.js';
const defaultRecentResultsProps = {
    initialState: {
        results: [],
    },
    options: {
        maxLength: 10,
    },
};
const initialStateSchema = new Schema({
    results: new ArrayValue({ required: true }),
});
const optionsSchema = new Schema({
    maxLength: new NumberValue({ required: true, min: 1 }),
});
export function validateRecentResultsProps(engine, props) {
    validateOptions(engine, optionsSchema, props?.options, 'buildRecentResultsList');
    validateInitialState(engine, initialStateSchema, props?.initialState, 'buildRecentResultsList');
}
/**
 * Creates a `RecentResultsList` controller instance.
 *
 * @param engine - The headless engine.
 * @param props - The configuration `RecentResultsList` properties.
 * @returns A `RecentResultsList` controller instance.
 *
 * @group Controllers
 * @category RecentResultsList
 * */
export function buildRecentResultsList(engine, props) {
    if (!loadRecentResultsListReducer(engine)) {
        throw loadReducerError;
    }
    const controller = buildController(engine);
    const { dispatch } = engine;
    const getState = () => engine.state;
    const registrationProps = {
        ...defaultRecentResultsProps,
        ...props,
    };
    validateRecentResultsProps(engine, registrationProps);
    const options = {
        results: registrationProps.initialState.results,
        maxLength: registrationProps.options.maxLength,
    };
    dispatch(registerRecentResults(options));
    return {
        ...controller,
        get state() {
            return getState().recentResults;
        },
        clear() {
            dispatch(logClearRecentResults());
            dispatch(clearRecentResults());
        },
    };
}
function loadRecentResultsListReducer(engine) {
    engine.addReducers({ recentResults });
    return true;
}
