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

const BCRYPT_ROUNDS = 12;

export function isLegacySha256Hash(passwordHash: string): boolean {
  return /^[a-f0-9]{64}$/i.test(passwordHash);
}

export async function hashPasswordForStorage(
  password: string,
  existingHash?: string
): Promise<string> {
  if (existingHash && isLegacySha256Hash(existingHash)) {
    const legacyMatches = crypto.createHash('sha256').update(password)
      .digest('hex') === existingHash;

    if (legacyMatches) {
      return bcrypt.hash(password, BCRYPT_ROUNDS);
    }
  }

  return bcrypt.hash(password, BCRYPT_ROUNDS);
}

export async function verifyPassword(password: string, passwordHash: string): Promise<boolean> {
  if (isLegacySha256Hash(passwordHash)) {
    return crypto.createHash('sha256').update(password)
      .digest('hex') === passwordHash;
  }

  return bcrypt.compare(password, passwordHash);
}
