package com.borjabolufer.elevate.utils;

import android.util.Log;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

  
public class PasswordUtils {

    private static final String TAG = "PasswordUtils";
    private static final String ALGORITHM = "PBKDF2WithHmacSHA256";
    private static final int ITERATION_COUNT = 65536;
    private static final int KEY_LENGTH = 256;
    private static final int SALT_SIZE = 16;

      
    public static String hashPassword(String password) {
        if (password == null || password.isEmpty()) {
            Log.e(TAG, "La contraseña no puede ser nula o vacía.");
            return null;
        }

        try {
            byte[] salt = new byte[SALT_SIZE];
            new SecureRandom().nextBytes(salt);

            KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH);
            SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
            byte[] hash = factory.generateSecret(spec).getEncoded();

            String saltBase64 = android.util.Base64.encodeToString(salt, android.util.Base64.NO_WRAP);
            String hashBase64 = android.util.Base64.encodeToString(hash, android.util.Base64.NO_WRAP);

            return saltBase64 + ":" + hashBase64;

        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            Log.e(TAG, "Error al hashear la contraseña", e);
            return null;
        }
    }

      
    public static boolean verifyPassword(String plainPassword, String storedPasswordWithSalt) {
        if (plainPassword == null || plainPassword.isEmpty() || storedPasswordWithSalt == null || storedPasswordWithSalt.isEmpty()) {
            Log.w(TAG, "Contraseña o hash almacenado vacío.");
            return false;
        }

        try {
            Log.d(TAG, "Hash recibido: " + storedPasswordWithSalt);
            Log.e(TAG, "Valor real recibido para verificar: [" + storedPasswordWithSalt + "]");
            String[] parts = storedPasswordWithSalt.split(":");
            if (parts.length != 2) {
                Log.e(TAG, "Formato de hash incorrecto. Se esperaba 'salt:hash'");
                return false;
            }

            byte[] salt = android.util.Base64.decode(parts[0], android.util.Base64.NO_WRAP);
            byte[] storedHash = android.util.Base64.decode(parts[1], android.util.Base64.NO_WRAP);

            KeySpec spec = new PBEKeySpec(plainPassword.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH);
            SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
            byte[] inputHash = factory.generateSecret(spec).getEncoded();

            return Arrays.equals(storedHash, inputHash);

        } catch (Exception e) {
            Log.e(TAG, "Error al verificar la contraseña", e);
            return false;
        }
    }
}
