/**
 * Encryption and Hashing Utilities
 *
 * Provides functions for password hashing, API key generation, and HMAC signatures
 */

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

// Constants
const BCRYPT_ROUNDS = 12;
const API_KEY_LENGTH = 32; // 32 bytes = 64 hex characters

/**
 * Hash a password using bcrypt
 */
export async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, BCRYPT_ROUNDS);
}

/**
 * Verify a password against a hash
 */
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return bcrypt.compare(password, hash);
}

/**
 * Generate a random API key with format: sk_live_{32_random_hex_chars}
 */
export function generateApiKey(prefix: string = 'sk_live'): { key: string; hash: string; prefix: string } {
  const randomBytes = crypto.randomBytes(API_KEY_LENGTH);
  const keySecret = randomBytes.toString('hex');
  const fullKey = `${prefix}_${keySecret}`;

  // Hash the full key for storage
  const hash = hashApiKey(fullKey);

  // Prefix for display (first 8 characters)
  const displayPrefix = fullKey.substring(0, Math.min(16, fullKey.length));

  return {
    key: fullKey,
    hash,
    prefix: displayPrefix,
  };
}

/**
 * Hash an API key using SHA-256
 */
export function hashApiKey(key: string): string {
  return crypto.createHash('sha256').update(key).digest('hex');
}

/**
 * Generate a random token for email verification or password reset
 */
export function generateToken(length: number = 32): string {
  return crypto.randomBytes(length).toString('hex');
}

/**
 * Generate HMAC signature for webhook payloads
 *
 * Format: timestamp.jobId.status
 * Signature: HMAC-SHA256(payload, secret)
 */
export function generateWebhookSignature(
  timestamp: string,
  jobId: string,
  status: string,
  secret: string
): string {
  const payload = `${timestamp}.${jobId}.${status}`;
  const hmac = crypto.createHmac('sha256', secret);
  hmac.update(payload);
  return hmac.digest('hex');
}

/**
 * Verify webhook signature
 */
export function verifyWebhookSignature(
  timestamp: string,
  jobId: string,
  status: string,
  secret: string,
  signature: string
): boolean {
  const expectedSignature = generateWebhookSignature(timestamp, jobId, status, secret);
  return crypto.timingSafeEqual(
    Buffer.from(signature, 'hex'),
    Buffer.from(expectedSignature, 'hex')
  );
}

/**
 * Generate content hash for deduplication
 */
export function generateContentHash(content: string, sourceLang: string, targetLang: string): string {
  const payload = `${content}.${sourceLang}.${targetLang}`;
  return crypto.createHash('sha256').update(payload).digest('hex');
}

/**
 * Generate secure random secret (for webhook callbacks)
 */
export function generateWebhookSecret(): string {
  return crypto.randomBytes(32).toString('hex');
}
