import crypto from 'crypto';

/**
 * Normalizes and hashes a string using SHA-256 according to Meta Conversions API specifications.
 * - Trims leading/trailing whitespace
 * - Converts to lowercase
 * - Leaves already hashed 64-character hex strings untouched
 */
export function hashMetaField(value?: string | null): string | undefined {
  if (!value) return undefined;
  const trimmed = value.trim().toLowerCase();
  if (!trimmed) return undefined;

  // If already a valid 64-char hex SHA-256 string, do not double-hash
  if (/^[a-f0-9]{64}$/.test(trimmed)) {
    return trimmed;
  }

  return crypto.createHash('sha256').update(trimmed).digest('hex');
}

/**
 * Normalizes phone numbers according to E.164 without symbols, then hashes.
 */
export function hashMetaPhone(phone?: string | null): string | undefined {
  if (!phone) return undefined;
  // If already hashed 64-char hex string
  if (/^[a-f0-9]{64}$/.test(phone.trim())) {
    return phone.trim().toLowerCase();
  }
  // Strip all non-numeric characters except leading +
  const cleaned = phone.replace(/[^0-9]/g, '');
  if (!cleaned) return undefined;
  return crypto.createHash('sha256').update(cleaned).digest('hex');
}

/**
 * Normalizes 2-letter ISO country code, then hashes.
 */
export function hashMetaCountry(country?: string | null): string | undefined {
  if (!country) return undefined;
  const clean = country.trim().toLowerCase().slice(0, 2);
  if (!clean) return undefined;
  return hashMetaField(clean);
}

/**
 * Normalizes 5-digit or standard postal code, then hashes.
 */
export function hashMetaZip(zip?: string | null): string | undefined {
  if (!zip) return undefined;
  // Strip spaces and lowercase
  const clean = zip.trim().toLowerCase().replace(/\s+/g, '');
  if (!clean) return undefined;
  return hashMetaField(clean);
}
