process.env.SECRET_ENC_KEY = process.env.SECRET_ENC_KEY || 'unit-test-enc-key'

const { test } = require('node:test')
const assert = require('node:assert/strict')

const secretBox = require('../src/utils/secretBox')

test('encrypt → decrypt round-trips a secret', () => {
  const plain = 'super-secret-oauth-client-secret'
  const enc = secretBox.encrypt(plain)
  assert.notEqual(enc, plain)
  assert.match(enc, /^[^:]+:[^:]+:[^:]+$/) // iv:tag:ct
  assert.equal(secretBox.decrypt(enc), plain)
})

test('ciphertext differs each call (random IV) but both decrypt', () => {
  const a = secretBox.encrypt('x')
  const b = secretBox.encrypt('x')
  assert.notEqual(a, b)
  assert.equal(secretBox.decrypt(a), 'x')
  assert.equal(secretBox.decrypt(b), 'x')
})

test('null/blank round-trips to null', () => {
  assert.equal(secretBox.encrypt(''), null)
  assert.equal(secretBox.encrypt(null), null)
  assert.equal(secretBox.decrypt(null), null)
  assert.equal(secretBox.decrypt(''), null)
})

test('tampered ciphertext fails authentication', () => {
  const enc = secretBox.encrypt('secret')
  const [iv, tag, ct] = enc.split(':')
  const tampered = `${iv}:${tag}:${Buffer.from('garbage').toString('base64')}`
  assert.throws(() => secretBox.decrypt(tampered))
  assert.throws(() => secretBox.decrypt('only:two')) // malformed
})
