const assert = require('assert');
const crypto = require('crypto');
const {
  decryptValidatorKeyEnvelopeForTest,
  encryptValidatorKeyEnvelope
} = require('../lib/validatorKeyEnvelope');

function main() {
  const pair = crypto.generateKeyPairSync('rsa', {
    modulusLength: 3072,
    publicKeyEncoding: { type: 'spki', format: 'der' },
    privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
  });
  const deviceKeyId = crypto.createHash('sha256').update(pair.publicKey).digest('hex');
  const validatorPrivateKey = crypto.randomBytes(32).toString('hex');
  const context = {
    chainId: 20260718,
    nodeName: 'synthetic-validator-1',
    pcName: 'synthetic-pc-1',
    genesisSha256: crypto.randomBytes(32).toString('hex')
  };
  const envelope = encryptValidatorKeyEnvelope({
    validatorPrivateKey,
    publicKeyBase64: pair.publicKey.toString('base64'),
    deviceKeyId,
    context
  });
  const recovered = decryptValidatorKeyEnvelopeForTest(envelope, pair.privateKey);
  assert.equal(recovered, validatorPrivateKey);
  assert.notEqual(envelope.ciphertext, Buffer.from(validatorPrivateKey).toString('base64'));

  const tampered = JSON.parse(JSON.stringify(envelope));
  tampered.context.nodeName = 'tampered-validator';
  assert.throws(() => decryptValidatorKeyEnvelopeForTest(tampered, pair.privateKey));
  assert.throws(() => encryptValidatorKeyEnvelope({
    validatorPrivateKey,
    publicKeyBase64: pair.publicKey.toString('base64'),
    deviceKeyId: crypto.randomBytes(32).toString('hex'),
    context
  }));
  const weakPair = crypto.generateKeyPairSync('rsa', {
    modulusLength: 2048,
    publicKeyEncoding: { type: 'spki', format: 'der' },
    privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
  });
  assert.throws(() => encryptValidatorKeyEnvelope({
    validatorPrivateKey,
    publicKeyBase64: weakPair.publicKey.toString('base64'),
    deviceKeyId: crypto.createHash('sha256').update(weakPair.publicKey).digest('hex'),
    context
  }));
  console.log(JSON.stringify({
    ok: true,
    algorithm: envelope.encryption,
    rsaBits: 3072,
    plaintextKeyWritten: false,
    roundTrip: 'pass',
    aadTamperRejected: true,
    wrongDeviceKeyRejected: true,
    weakRsaRejected: true
  }, null, 2));
}

try { main(); } catch (error) { console.error(error); process.exit(1); }
