/**
 * Privacy Utilities
 *
 * GDPR-compliant data handling utilities
 * Ensures PII is protected in logs and storage
 */

import crypto from 'crypto';
import { SECURITY_CONFIG } from '@/lib/config/constants';

/**
 * Hash an email address for privacy-compliant logging
 *
 * Creates a SHA-256 hash of the email and returns truncated hex string
 * This allows log correlation without storing PII
 *
 * @param email - Email address to hash
 * @returns Truncated hash (8 characters by default)
 *
 * @example
 * ```typescript
 * const hash = hashEmail('user@example.com');
 * logger.info('User action', { emailHash: hash }); // GDPR-compliant
 * ```
 */
export function hashEmail(email: string): string {
  return crypto
    .createHash('sha256')
    .update(email.toLowerCase().trim())
    .digest('hex')
    .substring(0, SECURITY_CONFIG.EMAIL_HASH_LENGTH);
}

/**
 * Hash any PII data for secure logging
 *
 * @param data - Sensitive data to hash
 * @param length - Hash length (default: 8)
 * @returns Truncated SHA-256 hash
 */
export function hashPII(data: string, length: number = 8): string {
  return crypto
    .createHash('sha256')
    .update(data.trim())
    .digest('hex')
    .substring(0, length);
}

/**
 * Mask email for display purposes
 *
 * Shows first 2 chars + domain
 *
 * @example
 * maskEmail('john.doe@example.com') // 'jo***@example.com'
 */
export function maskEmail(email: string): string {
  const [local, domain] = email.split('@');
  if (!domain) return '***';

  const maskedLocal = local.substring(0, 2) + '***';
  return `${maskedLocal}@${domain}`;
}

/**
 * Mask phone number for display
 *
 * Shows country code + last 4 digits
 *
 * @example
 * maskPhone('+971501234567') // '+971******4567'
 */
export function maskPhone(phone: string): string {
  if (phone.length < 8) return '***';

  const countryCode = phone.substring(0, phone.startsWith('+') ? 4 : 3);
  const lastFour = phone.substring(phone.length - 4);

  return `${countryCode}${'*'.repeat(phone.length - countryCode.length - 4)}${lastFour}`;
}
