import { randomBytes } from 'node:crypto';
import { assertSessionSecret } from './check-session-secret';

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

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

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

  it('returns the value when SESSION_SECRET decodes to ≥ 32 bytes', () => {
    process.env['SESSION_SECRET'] = STRONG_SECRET;
    expect(assertSessionSecret()).toBe(STRONG_SECRET);
  });

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

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

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