'use strict';

const bcrypt = require('bcryptjs');

const MIN_PASSWORD_LENGTH = 8;
const MAX_PASSWORD_LENGTH = 72;

function validatePassword(password) {
  const value = String(password || '');
  if (value.length < MIN_PASSWORD_LENGTH) return { ok: false, code: 'password_too_short', error: 'La contrasena debe tener al menos 8 caracteres.' };
  if (value.length > MAX_PASSWORD_LENGTH) return { ok: false, code: 'password_too_long', error: 'La contrasena no puede exceder 72 caracteres.' };
  if (!/[A-Za-z]/.test(value) || !/\d/.test(value)) return { ok: false, code: 'password_requires_letters_numbers', error: 'La contrasena debe incluir letras y numeros.' };
  return { ok: true };
}

function hashPassword(password) {
  const validation = validatePassword(password);
  if (!validation.ok) {
    const error = new Error(validation.error);
    error.code = validation.code;
    throw error;
  }
  return bcrypt.hashSync(String(password), 12);
}

function verifyPassword(password, password_hash) {
  if (!password_hash) return false;
  return bcrypt.compareSync(String(password || ''), String(password_hash));
}

function isValidPin(pin) {
  return /^\d{4,6}$/.test(String(pin || '').trim());
}

module.exports = {
  MIN_PASSWORD_LENGTH,
  MAX_PASSWORD_LENGTH,
  validatePassword,
  hashPassword,
  verifyPassword,
  isValidPin,
};
