import { randomBytes } from 'node:crypto';
import { assertSessionEncryptionKey } from './check-session-encryption-key';

const STRONG_KEY = randomBytes(32).toString('base64url');

describe('assertSessionEncryptionKey', () => {
  const original = process.env['SESSION_ENCRYPTION_KEY'];

  afterEach(() => {
    if (original === undefined) {
      delete process.env['SESSION_ENCRYPTION_KEY'];
    } else {
      process.env['SESSION_ENCRYPTION_KEY'] = original;
    }
  });

  it('returns the decoded 32-byte buffer for a well-formed key', () => {
    process.env['SESSION_ENCRYPTION_KEY'] = STRONG_KEY;
    const key = assertSessionEncryptionKey();
    expect(key).toBeInstanceOf(Buffer);
    expect(key.length).toBe(32);
    expect(key.equals(Buffer.from(STRONG_KEY, 'base64url'))).toBe(true);
  });

  it('throws when SESSION_ENCRYPTION_KEY is unset', () => {
    delete process.env['SESSION_ENCRYPTION_KEY'];
    expect(() => assertSessionEncryptionKey()).toThrow(/SESSION_ENCRYPTION_KEY is not set/);
  });

  it('throws when SESSION_ENCRYPTION_KEY is the .env.example placeholder', () => {
    process.env['SESSION_ENCRYPTION_KEY'] = 'replace_with_32_random_bytes_base64url';
    expect(() => assertSessionEncryptionKey()).toThrow(/placeholder/);
  });

  it('throws when SESSION_ENCRYPTION_KEY decodes to fewer than 32 bytes', () => {
    process.env['SESSION_ENCRYPTION_KEY'] = randomBytes(16).toString('base64url');
    expect(() => assertSessionEncryptionKey()).toThrow(/decodes to 16 bytes/);
  });

  it('throws when SESSION_ENCRYPTION_KEY decodes to more than 32 bytes', () => {
    process.env['SESSION_ENCRYPTION_KEY'] = randomBytes(64).toString('base64url');
    expect(() => assertSessionEncryptionKey()).toThrow(/decodes to 64 bytes/);
  });
});
