import { _ } from 'tnp-core/lib';
export class TaonStateMachine {
    config;
    _currentValue;
    constructor(config) {
        this.config = config;
        this._currentValue = config.defaultValue;
    }
    get debugMode() {
        return !!this.config?.debugMode;
    }
    get currentValue() {
        return this._currentValue;
    }
    canSet(nextStateRaw) {
        const nextState = this.config.modifyStateBeforeSetting?.(nextStateRaw, this._currentValue, this.debugMode) ?? nextStateRaw;
        if (!_.isMap(this.config.allowedStateMap)) {
            return true;
        }
        const allowed = this.config.allowedStateMap.get(this._currentValue) ?? [];
        return allowed.includes(nextState);
    }
    async set(nextStateRaw) {
        const previousState = this._currentValue;
        const nextState = this.config.modifyStateBeforeSetting?.(nextStateRaw, previousState, this.debugMode) ?? nextStateRaw;
        if (_.isMap(this.config.allowedStateMap)) {
            const allowed = this.config.allowedStateMap.get(previousState) ?? [];
            if (!allowed.includes(nextState)) {
                const message = `Invalid state transition: ${String(previousState)} -> ${String(nextState)}`;
                if (this.config.throwOnInvalidTransition) {
                    throw new Error(message);
                }
                this.debugMode && console.warn(message);
                return false;
            }
        }
        this._currentValue = nextState;
        await this.config.effect?.(nextState, previousState, this.debugMode);
        return true;
    }
}
//# sourceMappingURL=taon-build-state-machine.js.map