package at.procon.eventhub.dto;

import jakarta.validation.constraints.NotBlank;

/**
 * Describes the origin of an acquired event record.
 *
 * This is intentionally acquisition/source context. Equivalent real-world events
 * from different sources are kept as separate acquired records. Query/read
 * models can later combine sources when a preferred source contains gaps.
 */
public record EventSourceDto(
        @NotBlank String providerKey,
        @NotBlank String sourceKind,
        @NotBlank String sourceKey,
        String sourceInstanceKey,
        String tenantProviderSettingKey,
        String externalFleetKey
) {
    public EventSourceDto {
        providerKey = normalize(providerKey);
        sourceKind = normalize(sourceKind);
        sourceKey = normalize(sourceKey);
        sourceInstanceKey = normalizeNullable(sourceInstanceKey);
        tenantProviderSettingKey = normalizeNullable(tenantProviderSettingKey);
        externalFleetKey = normalizeNullable(externalFleetKey);
    }

    public String stableKey() {
        return String.join(":",
                providerKey,
                sourceKind,
                sourceKey,
                sourceInstanceKey == null ? "default" : sourceInstanceKey
        );
    }

    private static String normalize(String value) {
        if (value == null || value.isBlank()) {
            return value;
        }
        return value.trim().toUpperCase().replace('-', '_').replace(' ', '_');
    }

    private static String normalizeNullable(String value) {
        return value == null || value.isBlank() ? null : value.trim();
    }
}
