package click.kamil.enterprise.core;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractStateMachine<S extends Enum<S> & EnterpriseState, E extends Enum<E> & EnterpriseEvent> {
    
    private S currentState;
    private final Map<E, S> transitions = new ConcurrentHashMap<>();

    protected AbstractStateMachine(S initialState) {
        this.currentState = initialState;
        configureTransitions();
    }
    
    public abstract String getMachineType();
    
    protected abstract void configureTransitions();
    
    protected void addTransition(E event, S targetState) {
        transitions.put(event, targetState);
    }

    public synchronized void trigger(E event, TransitionContext<?> context) {
        S target = transitions.get(event);
        if (target == null) {
            throw new IllegalStateException("Invalid event " + event + " for state " + currentState);
        }
        
        executePreChecks(currentState, target, context);
        S oldState = currentState;
        currentState = target;
        onTransition(oldState, currentState, event, context);
    }
    
    protected void executePreChecks(S from, S to, TransitionContext<?> context) {
        // Parent checking logic
        System.out.println("[Abstract] Executing pre-checks from " + from.name() + " to " + to.name() + " by user " + context.getUserId());
    }
    
    protected abstract void onTransition(S from, S to, E event, TransitionContext<?> context);

    public S getCurrentState() {
        return currentState;
    }
    
    public Class<E> getEventType() {
        return (Class<E>) transitions.keySet().iterator().next().getClass();
    }
}
