import { ArrayValue, BooleanValue, NumberValue, Schema, StringValue, } from '@coveo/bueno';
import { stateKey } from '../../../app/state-key.js';
import { clearRecentQueries, registerRecentQueries, } from '../../../features/commerce/recent-queries/recent-queries-actions.js';
import { recentQueriesReducer as recentQueries } from '../../../features/commerce/recent-queries/recent-queries-slice.js';
import { executeSearch, prepareForSearchWithQuery, } from '../../../features/commerce/search/search-actions.js';
import { commerceSearchReducer as search } from '../../../features/commerce/search/search-slice.js';
import { loadReducerError } from '../../../utils/errors.js';
import { validateInitialState, validateOptions, } from '../../../utils/validate-payload.js';
import { buildController, } from '../../controller/headless-controller.js';
const defaultRecentQueriesState = {
    queries: [],
};
const defaultRecentQueriesOptions = {
    maxLength: 10,
    clearFilters: true,
    enableResults: false,
};
const initialStateSchema = new Schema({
    queries: new ArrayValue({ required: true }),
});
const optionsSchema = new Schema({
    maxLength: new NumberValue({ required: true, min: 1 }),
    clearFilters: new BooleanValue(),
    enableResults: new BooleanValue(),
});
function validateRecentQueriesProps(engine, props) {
    validateOptions(engine, optionsSchema, props?.options, 'buildRecentQueriesList');
    validateInitialState(engine, initialStateSchema, props?.initialState, 'buildRecentQueriesList');
}
/**
 * Creates a `RecentQueriesList` controller instance.
 *
 * @param engine - The headless engine.
 * @param props - The configuration `RecentQueriesList` properties.
 * @returns A `RecentQueriesList` controller instance.
 *
 * @group Buildable controllers
 * @category RecentQueriesList
 *
 * */
export function buildRecentQueriesList(engine, props) {
    if (!loadRecentQueriesListReducer(engine)) {
        throw loadReducerError;
    }
    const controller = buildController(engine);
    const { dispatch } = engine;
    const getState = () => engine[stateKey];
    const registrationOptions = {
        ...defaultRecentQueriesOptions,
        ...props?.options,
    };
    const registrationState = {
        ...defaultRecentQueriesState,
        ...props?.initialState,
    };
    validateRecentQueriesProps(engine, {
        options: registrationOptions,
        initialState: registrationState,
    });
    const options = {
        queries: registrationState.queries,
        maxLength: registrationOptions.maxLength,
    };
    dispatch(registerRecentQueries(options));
    return {
        ...controller,
        get state() {
            const state = getState();
            return {
                ...state.recentQueries,
                analyticsEnabled: state.configuration.analytics.enabled,
            };
        },
        clear() {
            dispatch(clearRecentQueries());
        },
        updateRecentQueries(queries) {
            const errorMessage = new ArrayValue({
                required: true,
                each: new StringValue({ required: true }),
                min: 1,
            }).validate(queries);
            if (errorMessage) {
                throw new Error(errorMessage);
            }
            dispatch(registerRecentQueries({
                queries,
                maxLength: registrationOptions.maxLength,
            }));
        },
        executeRecentQuery(index) {
            const errorMessage = new NumberValue({
                required: true,
                min: 0,
                max: this.state.queries.length,
            }).validate(index);
            if (errorMessage) {
                throw new Error(errorMessage);
            }
            const queryOptions = {
                query: this.state.queries[index],
                clearFilters: registrationOptions.clearFilters,
            };
            dispatch(prepareForSearchWithQuery(queryOptions));
            dispatch(executeSearch({ enableResults: registrationOptions.enableResults }));
        },
    };
}
function loadRecentQueriesListReducer(engine) {
    engine.addReducers({ search, recentQueries });
    return true;
}
