package com.airlock.iam.login.app.infrastructure.event;

import com.airlock.iam.flow.domain.model.event.GenericStepResultEvent;
import java.util.HashMap;
import java.util.Map;

public final class GenericStepResultEventValuesProvider {
   public static Map<String, Object> provideValues(GenericStepResultEvent event) {
      Map<String, Object> values = new HashMap<>();
      values.put("event.data.stepResult.type", event.stepResultType().name());
      event.stepAction().ifPresent(action -> values.put("event.data.stepResult.nextAction", action.name()));
      event.stepError().ifPresent(error -> values.put("event.data.stepResult.errorCode", error.name()));
      event.additionalAttributes().forEach((key, value) -> addAttribute(values, "event.data.stepResult.attributes." + key, value));
      return Map.copyOf(values);
   }

   private static void addAttribute(Map<String, Object> values, String key, Object value) {
      if (value != null) {
         if (value instanceof Map map) {
            map.forEach((mapKey, mapValue) -> addAttribute(values, key + "." + mapKey, mapValue));
         } else {
            values.put(key, value);
         }
      }
   }

   private GenericStepResultEventValuesProvider() {
   }
}
