package com.airlock.iam.flow.shared.infrastructure.mapper;

import com.airlock.iam.common.infrastructure.event.EventPayloadData;
import com.airlock.iam.common.infrastructure.event.EventPayloadSource;
import com.airlock.iam.flow.api.domain.model.event.FlowEventSource;
import com.airlock.iam.flow.domain.model.event.GenericStepResultEvent;
import com.airlock.iam.plugin.api.event.ConfigurationContextEventSource;
import java.util.HashMap;
import java.util.Map;
import org.mapstruct.Mapper;

@Mapper
public interface FlowEventMapper {
   default EventPayloadData mapGenericStepResultEvent(GenericStepResultEvent event) {
      Map<String, Object> data = new HashMap<>();
      data.put("stepResultType", event.stepResultType().name());
      event.stepAction().ifPresent(action -> data.put("nextAction", action.name()));
      event.stepError().ifPresent(error -> data.put("errorCode", error.name()));
      return new EventPayloadData(data);
   }

   default EventPayloadSource mapFlowEventSource(FlowEventSource source) {
      Map<String, Object> map = new HashMap<>();
      map.put("sourceType", "flow");
      map.put("flowType", source.flowType().name());
      map.put("flowId", source.flowId().getFlowId());
      source.stepId().ifPresent(stepId -> map.put("stepId", stepId.getStepId()));
      if (source instanceof ConfigurationContextEventSource contextSource) {
         map.put("configurationContext", contextSource.configurationContext().toString());
      }

      return new EventPayloadSource(map);
   }
}
