import bcrypt from 'bcryptjs';
import crypto from 'crypto';

/**
 * Hashuje heslo pomocou bcrypt
 * @param {string} password - Plain text heslo
 * @returns {Promise<string>} Hashované heslo
 */
export const hashPassword = async (password) => {
  const rounds = parseInt(process.env.BCRYPT_ROUNDS) || 12;
  return bcrypt.hash(password, rounds);
};

/**
 * Porovná plain text heslo s hash
 * @param {string} password - Plain text heslo
 * @param {string} hash - Hashované heslo
 * @returns {Promise<boolean>} True ak sa zhodujú
 */
export const comparePassword = async (password, hash) => {
  return bcrypt.compare(password, hash);
};

/**
 * Generuje náhodné dočasné heslo
 * Používa len bezpečné znaky (bez problematických ako #, $, %, &, atď.)
 * @param {number} length - Dĺžka hesla (default: 12)
 * @returns {string} Náhodné heslo
 */
export const generateTempPassword = (length = 12) => {
  const uppercase = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; // bez I, O (ľahko zameniteľné)
  const lowercase = 'abcdefghjkmnpqrstuvwxyz'; // bez i, l, o (ľahko zameniteľné)
  const numbers = '23456789'; // bez 0, 1 (ľahko zameniteľné)
  const all = uppercase + lowercase + numbers;

  let password = '';

  // Zaručí aspoň jeden znak z každej kategórie
  password += uppercase[Math.floor(Math.random() * uppercase.length)];
  password += lowercase[Math.floor(Math.random() * lowercase.length)];
  password += numbers[Math.floor(Math.random() * numbers.length)];

  // Zvyšok náhodne
  for (let i = password.length; i < length; i++) {
    password += all[Math.floor(Math.random() * all.length)];
  }

  // Zamieša znaky
  return password
    .split('')
    .sort(() => Math.random() - 0.5)
    .join('');
};

/**
 * Generuje náhodný verification token
 * @returns {string} UUID token
 */
export const generateVerificationToken = () => {
  return crypto.randomUUID();
};

/**
 * Encrypt emailPassword using AES-256-GCM
 * @param {string} text - Plain text password
 * @returns {string} Encrypted password in format: iv:authTag:encrypted
 */
export const encryptPassword = (text) => {
  if (!process.env.EMAIL_ENCRYPTION_KEY) {
    throw new Error('EMAIL_ENCRYPTION_KEY environment variable is required for password encryption');
  }
  if (!process.env.ENCRYPTION_SALT) {
    throw new Error('ENCRYPTION_SALT environment variable is required for password encryption');
  }
  if (process.env.ENCRYPTION_SALT.length < 32) {
    throw new Error('ENCRYPTION_SALT must be at least 32 characters');
  }

  const algorithm = 'aes-256-gcm';
  const key = crypto.scryptSync(process.env.EMAIL_ENCRYPTION_KEY, process.env.ENCRYPTION_SALT, 32);
  const iv = crypto.randomBytes(16);

  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');

  const authTag = cipher.getAuthTag();

  return `${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`;
};

/**
 * Decrypt emailPassword
 * @param {string} encryptedText - Encrypted password in format: iv:authTag:encrypted
 * @returns {string} Plain text password
 */
export const decryptPassword = (encryptedText) => {
  if (!process.env.EMAIL_ENCRYPTION_KEY) {
    throw new Error('EMAIL_ENCRYPTION_KEY environment variable is required for password decryption');
  }
  if (!process.env.ENCRYPTION_SALT) {
    throw new Error('ENCRYPTION_SALT environment variable is required for password decryption');
  }
  if (process.env.ENCRYPTION_SALT.length < 32) {
    throw new Error('ENCRYPTION_SALT must be at least 32 characters');
  }

  const algorithm = 'aes-256-gcm';
  const key = crypto.scryptSync(process.env.EMAIL_ENCRYPTION_KEY, process.env.ENCRYPTION_SALT, 32);

  const parts = encryptedText.split(':');
  const iv = Buffer.from(parts[0], 'hex');
  const authTag = Buffer.from(parts[1], 'hex');
  const encrypted = parts[2];

  const decipher = crypto.createDecipheriv(algorithm, key, iv);
  decipher.setAuthTag(authTag);

  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');

  return decrypted;
};
