package backend.utils.impl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class PasswordUtils {
    private static final String PREFIX = "encrypted_";
    private static final SecureRandom random = new SecureRandom();

    /**
     * 对明文密码进行加密处理
     *
     * @param plainText 需要加密的明文密码字符串
     * @return 加密后的密码字符串
     */
    public static String encrypt(String plainText){
        if (plainText == null) {
            throw new IllegalArgumentException("密码不能为空");
        }

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] salt = new byte[16];
            random.nextBytes(salt);
            md.update(salt);

            byte[] hashedPassword = md.digest(plainText.getBytes());
            StringBuilder sb = new StringBuilder();
            sb.append(PREFIX);
            for (byte b : salt) {
                sb.append(String.format("%02x", b));
            }
            for (byte b : hashedPassword) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 algorithm not available", e);
        }
    }

    /**
     * 验证明文密码与已加密密码是否匹配
     *
     * @param plainText 明文密码字符串
     * @param hashed 已加密的密码字符串
     * @return 如果匹配返回true，否则返回false
     */
    public static boolean verify(String plainText, String hashed){
        if (plainText == null || hashed == null) {
            return false;
        }

        if (!hashed.startsWith(PREFIX)) {
            return false;
        }

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            String hashWithoutPrefix = hashed.substring(PREFIX.length());

            if (hashWithoutPrefix.length() < 32) {
                return false;
            }

            String saltHex = hashWithoutPrefix.substring(0, 32);
            String storedHashHex = hashWithoutPrefix.substring(32);

            byte[] salt = new byte[16];
            for (int i = 0; i < 16; i++) {
                salt[i] = (byte) Integer.parseInt(saltHex.substring(i * 2, i * 2 + 2), 16);
            }

            md.update(salt);
            byte[] hashedPassword = md.digest(plainText.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : hashedPassword) {
                sb.append(String.format("%02x", b));
            }

            return sb.toString().equals(storedHashHex);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 algorithm not available", e);
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
