package at.procon.eventhub.processing.eventprocessing.module.epl;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public record RuntimeEplModuleExecutionResult(
        Map<String, List<Map<String, Object>>> outputsByStatement,
        Map<String, Object> metadata
) {
    public RuntimeEplModuleExecutionResult {
        outputsByStatement = outputsByStatement == null ? Map.of() : immutableOutputMap(outputsByStatement);
        metadata = metadata == null ? Map.of() : Collections.unmodifiableMap(new LinkedHashMap<>(metadata));
    }

    public List<Map<String, Object>> output(String statementName) {
        return outputsByStatement.getOrDefault(statementName, List.of());
    }

    private static Map<String, List<Map<String, Object>>> immutableOutputMap(Map<String, List<Map<String, Object>>> source) {
        LinkedHashMap<String, List<Map<String, Object>>> copy = new LinkedHashMap<>();
        source.forEach((key, value) -> copy.put(key, value == null ? List.of() : List.copyOf(value)));
        return Collections.unmodifiableMap(copy);
    }
}
