import assert from 'node:assert/strict';
import test from 'node:test';

import {
  decryptSecret,
  encryptSecret,
} from '../../features/foundation/secrets/server/crypto.ts';

const previousKey = process.env.EMAIL_CONFIG_ENCRYPTION_KEY;

test.before(() => {
  process.env.EMAIL_CONFIG_ENCRYPTION_KEY =
    '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
});

test.after(() => {
  if (typeof previousKey === 'string') {
    process.env.EMAIL_CONFIG_ENCRYPTION_KEY = previousKey;
    return;
  }

  delete process.env.EMAIL_CONFIG_ENCRYPTION_KEY;
});

test('encryptSecret output decrypts back to the original value', () => {
  const encrypted = encryptSecret('smtp-password');

  assert.match(encrypted, /^enc:v1:/);
  assert.equal(decryptSecret(encrypted), 'smtp-password');
});

test('decryptSecret rejects malformed ciphertext', () => {
  assert.throws(
    () => decryptSecret('enc:v1:missing-parts'),
    /Encrypted secret format is invalid\./,
  );
});
