package p.packer.repositories;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

public final class PackerContractFingerprint {
    private PackerContractFingerprint() {
    }

    public static String metadataFingerprint(Map<String, String> metadata) {
        final var normalized = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
        Objects.requireNonNull(metadata, "metadata").forEach((key, value) -> {
            if (key == null || key.isBlank()) {
                return;
            }
            normalized.put(key.trim(), value == null ? "" : value);
        });
        final String canonical = normalized.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .reduce((left, right) -> left + "\n" + right)
                .orElse("");
        try {
            return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
                    .digest(canonical.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException exception) {
            throw new IllegalStateException("SHA-256 contract fingerprint is unavailable", exception);
        }
    }
}
