import * as argon2 from 'argon2';
import bcrypt from 'bcryptjs';

// Password hashing with Argon2 (spec requirement)
export async function hashPassword(password: string): Promise<string> {
  return argon2.hash(password, {
    type: argon2.argon2id,
    memoryCost: 65536, // 64 MB
    timeCost: 3,
    parallelism: 4,
  });
}

export async function verifyPassword(password: string, hash: string): Promise<boolean> {
  // Support both bcrypt (legacy) and argon2 hashes for migration
  if (hash.startsWith('$argon2')) {
    return argon2.verify(hash, password);
  }
  // Legacy bcrypt support
  return bcrypt.compare(password, hash);
}

// Small blocklist of common/weak passwords (and obvious app-specific ones).
// Compared case-insensitively after stripping non-alphanumerics so that e.g.
// "P@ssw0rd!" still matches "password".
const COMMON_PASSWORDS = new Set([
  'password', 'passw0rd', '123456', '1234567', '12345678', '123456789', '1234567890',
  'qwerty', 'qwertyuiop', 'letmein', 'welcome', 'admin', 'administrator', 'iloveyou',
  'monkey', 'dragon', 'sunshine', 'princess', 'football', 'baseball', 'abc123',
  'spanglish', 'changeme', 'secret', 'master', 'login', 'access',
]);

// Password policy: 10-128 chars, requires a mix of character types, and rejects
// common/weak passwords. Centralized so register/reset/change all share it.
export function validatePassword(password: string): { valid: boolean; error?: string } {
  if (password.length < 10) {
    return { valid: false, error: 'Password must be at least 10 characters long' };
  }
  if (password.length > 128) {
    return { valid: false, error: 'Password must be at most 128 characters long' };
  }

  const hasLower = /[a-z]/.test(password);
  const hasUpper = /[A-Z]/.test(password);
  const hasDigit = /\d/.test(password);
  const hasSymbol = /[^A-Za-z0-9]/.test(password);

  // Require lowercase, uppercase, and at least one digit or symbol.
  if (!hasLower || !hasUpper || !(hasDigit || hasSymbol)) {
    return {
      valid: false,
      error: 'Password must include uppercase and lowercase letters and at least one number or symbol',
    };
  }

  const normalized = password.toLowerCase().replace(/[^a-z0-9]/g, '');
  if (COMMON_PASSWORDS.has(normalized)) {
    return { valid: false, error: 'Password is too common. Please choose a less guessable password.' };
  }

  return { valid: true };
}
