import { stateKey } from '../../../app/state-key.js';
import { setContext, setLocation, setView, } from '../../../features/commerce/context/context-actions.js';
import { contextReducer as commerceContext } from '../../../features/commerce/context/context-slice.js';
import { contextSchema } from '../../../features/commerce/context/context-validation.js';
import { loadReducerError } from '../../../utils/errors.js';
import { validateOptions } from '../../../utils/validate-payload.js';
import { buildController, } from '../../controller/headless-controller.js';
/**
 * Creates a `Context` controller instance.
 *
 * @param engine - The headless commerce engine.
 * @param props - The configurable `Context` properties.
 * @returns A `Context` controller instance.
 *
 * @group Buildable controllers
 * @category Context
 */
export function buildContext(engine, props = {}) {
    if (!loadBaseContextReducers(engine)) {
        throw loadReducerError;
    }
    const controller = buildController(engine);
    const { dispatch } = engine;
    const getState = () => engine[stateKey];
    if (props.options) {
        validateOptions(engine, contextSchema, props.options, 'buildContext');
        dispatch(setContext(props.options));
    }
    return {
        ...controller,
        get state() {
            return getState().commerceContext;
        },
        setLanguage: (language) => dispatch(setContext({
            ...getState().commerceContext,
            language,
        })),
        setCountry: (country) => dispatch(setContext({
            ...getState().commerceContext,
            country,
        })),
        setCurrency: (currency) => dispatch(setContext({
            ...getState().commerceContext,
            currency,
        })),
        setView: (view) => dispatch(setView(view)),
        setLocation: (location) => dispatch(setLocation(location)),
    };
}
function loadBaseContextReducers(engine) {
    engine.addReducers({ commerceContext });
    return true;
}
