// Reversible AES-256-CBC decryption used to reveal sensitive fields (e.g. lead phone_number)
// that the backend encrypts before sending them in API responses (see
// helpers/encryption.helper.js on the backend). Uses the browser's native Web Crypto API
// (SubtleCrypto) since Node's `crypto` module is not available on the client.
// The backend produces values in the "iv:ciphertext" hex format; this must be decrypted
// using the exact same PHONE_ENCRYPTION_KEY shared between frontend and backend.

const ALGORITHM = 'AES-CBC';

/** Converts a hex string into a Uint8Array of bytes. */
const hexToBytes = (hex: string): Uint8Array => {
  const bytes = new Uint8Array(hex.length / 2);
  for (let i = 0; i < hex.length; i += 2) {
    bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
  }
  return bytes;
};

/** Builds the AES-256-CBC key buffer from the shared 64-char hex PHONE_ENCRYPTION_KEY. */
const getKeyBytes = (): Uint8Array => {
  const key = process.env.PHONE_ENCRYPTION_KEY;
  if (!key) {
    throw new Error('PHONE_ENCRYPTION_KEY is not configured in environment variables');
  }
  const keyBytes = hexToBytes(key);
  if (keyBytes.length !== 32) {
    throw new Error('PHONE_ENCRYPTION_KEY must be a 64-character hex string (32 bytes) for AES-256-CBC');
  }
  return keyBytes;
};

/**
 * Decrypts a value previously produced by the backend's encrypt() helper.
 * Expects the "iv:ciphertext" hex format. Resolves to null on malformed input or when
 * Web Crypto is unavailable, instead of throwing, so callers can decide how to handle it.
 */
export const decryptPhoneNumber = async(
  encryptedText: string | null | undefined
): Promise<string | null> => {
  if (encryptedText === null || encryptedText === undefined || encryptedText === '') {
    return (encryptedText as string | null) ?? null;
  }

  const parts = String(encryptedText).split(':');
  if (parts.length !== 2) {
    return null;
  }
  const [ivHex, encryptedHex] = parts;

  try {
    if (typeof window === 'undefined' || !window.crypto?.subtle) {
      return null;
    }

    const keyBytes = getKeyBytes();
    const iv = hexToBytes(ivHex);
    const encryptedBytes = hexToBytes(encryptedHex);

    const cryptoKey = await window.crypto.subtle.importKey(
      'raw',
      keyBytes,
      { name: ALGORITHM },
      false,
      ['decrypt']
    );

    const decryptedBuffer = await window.crypto.subtle.decrypt(
      { name: ALGORITHM, iv },
      cryptoKey,
      encryptedBytes
    );

    return new TextDecoder('utf-8').decode(decryptedBuffer);
  } catch {
    return null;
  }
};
