import {
  constants,
  createDecipheriv,
  createCipheriv,
  createHmac,
  privateDecrypt,
  timingSafeEqual,
} from 'crypto';

export function validFlowSignature(
  raw: Buffer | undefined,
  signature: string | undefined,
  secret: string,
): boolean {
  if (!raw || !secret || !signature || !/^sha256=[a-f0-9]{64}$/.test(signature))
    return false;
  const expected = createHmac('sha256', secret).update(raw).digest();
  return timingSafeEqual(expected, Buffer.from(signature.slice(7), 'hex'));
}

export function decryptFlow(body: any, key: string, passphrase?: string) {
  for (const field of [
    'encrypted_aes_key',
    'encrypted_flow_data',
    'initial_vector',
  ]) {
    if (typeof body?.[field] !== 'string' || body[field].length > 150_000)
      throw new Error('Invalid envelope');
  }
  const aes = privateDecrypt(
    {
      key,
      passphrase,
      padding: constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: 'sha256',
    },
    Buffer.from(body.encrypted_aes_key, 'base64'),
  );
  const iv = Buffer.from(body.initial_vector, 'base64');
  const ciphertext = Buffer.from(body.encrypted_flow_data, 'base64');
  const decipher = createDecipheriv('aes-128-gcm', aes, iv);
  decipher.setAuthTag(ciphertext.subarray(-16));
  const data = JSON.parse(
    Buffer.concat([
      decipher.update(ciphertext.subarray(0, -16)),
      decipher.final(),
    ]).toString('utf8'),
  );
  return { aes, iv, data };
}

export function encryptFlow(data: unknown, aes: Buffer, iv: Buffer) {
  const cipher = createCipheriv(
    'aes-128-gcm',
    aes,
    Buffer.from(iv.map((byte) => byte ^ 255)),
  );
  return Buffer.concat([
    cipher.update(JSON.stringify(data), 'utf8'),
    cipher.final(),
    cipher.getAuthTag(),
  ]).toString('base64');
}
