package com.foxx.androidcast;

/*********************************************************************
 * PinAuth.java
 * Created at: Sun 17 May 2026 18:17:14 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class PinAuth
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 45 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	3641153433384df49669b313d653fbb49335b7c7b8d002c671bcf994215e5896
**********************************************************************/
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/** PIN hashing for discovery and handshake (never send raw PIN on LAN). */
public final class PinAuth {
    private PinAuth() {}

    public static String hash(String pin) {
        if (pin == null) {
            pin = "";
        }
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] digest = md.digest(pin.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder(digest.length * 2);
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            return Integer.toHexString(pin.hashCode());
        }
    }

    public static boolean matches(String pin, String expectedHash) {
        if (expectedHash == null || expectedHash.isEmpty()) {
            return true;
        }
        return hash(pin).equals(expectedHash);
    }

    public static boolean isProtected(String pin) {
        return pin != null && !pin.isEmpty();
    }
}
