import * as crypto from 'crypto';
import * as bcrypt from 'bcrypt';

export class HashUtil {
  /**
   * Generate SHA-256 hash from buffer
   */
  static sha256(buffer: Buffer): string {
    return crypto.createHash('sha256').update(buffer).digest('hex');
  }

  /**
   * Generate SHA-256 hash from string
   */
  static sha256String(input: string): string {
    return crypto.createHash('sha256').update(input).digest('hex');
  }

  /**
   * Generate Keccak-256 hash (Ethereum compatible)
   */
  static keccak256(input: string): string {
    return crypto.createHash('sha3-256').update(input).digest('hex');
  }

  /**
   * Hash password using bcrypt
   */
  static async hashPassword(password: string, rounds = 10): Promise<string> {
    return bcrypt.hash(password, rounds);
  }

  /**
   * Compare password with hash
   */
  static async comparePassword(password: string, hash: string): Promise<boolean> {
    return bcrypt.compare(password, hash);
  }

  /**
   * Generate secure random API key
   */
  static generateApiKey(): string {
    return crypto.randomBytes(32).toString('hex');
  }

  /**
   * Generate secure random secret
   */
  static generateSecret(): string {
    return crypto.randomBytes(48).toString('base64url');
  }

  /**
   * Generate HMAC signature for webhooks
   */
  static generateHmacSignature(payload: string, secret: string): string {
    return crypto.createHmac('sha256', secret).update(payload).digest('hex');
  }

  /**
   * Verify HMAC signature
   */
  static verifyHmacSignature(payload: string, secret: string, signature: string): boolean {
    const expectedSignature = this.generateHmacSignature(payload, secret);
    return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature));
  }

  /**
   * Generate UUID v4
   */
  static generateUuid(): string {
    return crypto.randomUUID();
  }
}
