package com.airlock.iam.flow.domain.model.statemachine.spring;

import com.airlock.iam.flow.api.domain.model.step.FlowStep;
import com.airlock.iam.flow.api.domain.model.step.StepResult;
import com.airlock.iam.flow.domain.model.event.StateMachineFlowEvent;
import com.airlock.iam.flow.domain.model.statemachine.FlowState;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import jakarta.inject.Provider;
import java.util.function.BiConsumer;
import lombok.NonNull;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.action.Action;

public class CurrentStepAction implements Action<FlowState, StateMachineFlowEvent> {
   @NonNull
   private final BiConsumer<FlowStep, StepResult> action;
   @NonNull
   private final Provider<FlowStep> step;

   public void execute(StateContext<FlowState, StateMachineFlowEvent> context) {
      StepResult stepResultToBeProcessed = StepResultExtractor.extractStepResult(context);
      this.action.accept((FlowStep)this.step.get(), stepResultToBeProcessed);
   }

   public static CurrentStepAction currentStepAction(BiConsumer<FlowStep, StepResult> action, StepContext stepContext) {
      return new CurrentStepAction(action, stepContext.getStep());
   }

   @SuppressFBWarnings(justification = "generated code")
   private CurrentStepAction(@NonNull BiConsumer<FlowStep, StepResult> action, @NonNull Provider<FlowStep> step) {
      if (action == null) {
         throw new NullPointerException("action is marked non-null but is null");
      }

      if (step == null) {
         throw new NullPointerException("step is marked non-null but is null");
      }

      this.action = action;
      this.step = step;
   }
}
