import { addContext, removeContext, } from '../../../features/context/context-actions.js';
import { contextReducer as context } from '../../../features/context/context-slice.js';
import { loadReducerError } from '../../../utils/errors.js';
import { isReservedContextKey, UnreservedContextKeyError, } from './headless-context-reserved-keys.js';
/**
 * Creates an `InternalContext` controller instance
 *
 * @param engine - The headless engine.
 * @param props - The configurable `Context` controller properties.
 * @internal
 * @returns a `Context` controller instance.
 */
export function buildInternalCoreContext(engine) {
    if (!loadContextReducers(engine)) {
        throw loadReducerError;
    }
    const { dispatch } = engine;
    return {
        add(contextKey, contextValue) {
            if (!isReservedContextKey(contextKey)) {
                throw new UnreservedContextKeyError(contextKey);
            }
            dispatch(addContext({ contextKey, contextValue }));
        },
        remove(contextKey) {
            if (!isReservedContextKey(contextKey)) {
                throw new UnreservedContextKeyError(contextKey);
            }
            dispatch(removeContext(contextKey));
        },
    };
}
function loadContextReducers(engine) {
    engine.addReducers({ context });
    return true;
}
