import { randomBytes } from 'node:crypto';
import { assertLogUserIdSalt } from './check-log-user-id-salt';

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

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

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

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

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

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

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