package at.procon.eventhub.processing.eventprocessing.profile;

import at.procon.eventhub.processing.eventprocessing.dto.RuntimeEventProcessingProfileDescriptorDto;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

@Component
public class RuntimeEventProcessingProfileRegistry {

    private final Map<String, RuntimeEventProcessingProfile> profilesByKey;

    public RuntimeEventProcessingProfileRegistry(List<RuntimeEventProcessingProfile> profiles) {
        LinkedHashMap<String, RuntimeEventProcessingProfile> byKey = new LinkedHashMap<>();
        for (RuntimeEventProcessingProfile profile : profiles == null ? List.<RuntimeEventProcessingProfile>of() : profiles) {
            String key = profile.profileKey();
            if (key == null || key.isBlank()) {
                throw new IllegalStateException("Runtime event processing profile returned a blank profileKey: " + profile.getClass().getName());
            }
            RuntimeEventProcessingProfile previous = byKey.putIfAbsent(key, profile);
            if (previous != null) {
                throw new IllegalStateException("Duplicate runtime event processing profileKey: " + key);
            }
        }
        this.profilesByKey = Collections.unmodifiableMap(byKey);
    }

    public RuntimeEventProcessingProfile require(String profileKey) {
        String normalized = profileKey == null ? null : profileKey.trim();
        RuntimeEventProcessingProfile profile = normalized == null ? null : profilesByKey.get(normalized);
        if (profile == null) {
            throw new IllegalArgumentException("Unknown runtime event processing profileKey: " + profileKey
                    + ". Available profiles: " + profilesByKey.keySet());
        }
        return profile;
    }

    public Map<String, RuntimeEventProcessingProfile> profilesByKey() {
        return profilesByKey;
    }

    public List<RuntimeEventProcessingProfileDescriptorDto> profileDescriptors() {
        return profilesByKey.values().stream()
                .map(RuntimeEventProcessingProfileDescriptorDto::from)
                .toList();
    }
}
