package ru.kirillius.pf.sdn.core.Util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Provides hashing helpers for password management and compatibility utilities.
 */
public final class HashUtil {
    private HashUtil() {
    }

    /**
     * Computes the MD5 digest for the supplied input string.
     */
    public static String md5(String input) {
        try {
            var md = MessageDigest.getInstance("MD5");
            var hash = md.digest(input.getBytes());


            var hexString = new StringBuilder();
            for (var b : hash) {
                var hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    /**
     * Computes a salted SHA-512 hash, returning the hexadecimal representation.
     */
    public static String hash(String data, String salt) {
        String generatedPassword = null;
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-512");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        md.update(salt.getBytes(StandardCharsets.UTF_8));
        var bytes = md.digest(data.getBytes(StandardCharsets.UTF_8));
        var sb = new StringBuilder();
        for (byte aByte : bytes) {
            sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
        }
        generatedPassword = sb.toString();
        return generatedPassword;

    }
}
