/**
 * AES-GCM field decryption matching Botmaster's `db-crypto.ts` (ivHex:ctHex,
 * 12-byte IV, key = hex-encoded raw AES-256 key). Kept in sync by hand — the
 * two repos do not share code.
 */

async function getCryptoKey(encKeyHex: string): Promise<CryptoKey> {
  const raw = new Uint8Array(encKeyHex.match(/.{2}/g)!.map((b) => parseInt(b, 16)));
  return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["decrypt"]);
}

export async function decryptField(keyHex: string, cipher: string): Promise<string> {
  if (!cipher || !cipher.includes(":")) return cipher;
  const key = await getCryptoKey(keyHex);
  const [ivHex, ctHex] = cipher.split(":");
  const iv = new Uint8Array(ivHex!.match(/.{2}/g)!.map((b) => parseInt(b, 16)));
  const ct = new Uint8Array(ctHex!.match(/.{2}/g)!.map((b) => parseInt(b, 16)));
  const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ct);
  return new TextDecoder().decode(plain);
}
