import { resolveRabbitMqConfig } from './rabbitmq';

const source = (values: Record<string, string>) => ({ get: (key: string) => values[key] });

describe('RabbitMQ production configuration', () => {
  it('rejects guest credentials and plaintext in production microservices', () => {
    expect(() => resolveRabbitMqConfig(source({ NODE_ENV: 'production', RABBITMQ_URL: 'amqps://guest:guest@broker/vhost' }), 'gateway', true)).toThrow('non-guest');
    expect(() => resolveRabbitMqConfig(source({ NODE_ENV: 'production', RABBITMQ_URL: 'amqp://service:strong-password@broker/vhost' }), 'gateway', true)).toThrow('TLS/amqps');
  });

  it('supports secure URLs and separate TLS credentials without exposing userinfo', () => {
    const direct = resolveRabbitMqConfig(source({
      NODE_ENV: 'production', RABBITMQ_URL: 'amqps://service:strong-password@broker.example/vhost',
      RABBITMQ_SERVERNAME: 'broker.example', RABBITMQ_TLS_REJECT_UNAUTHORIZED: 'true',
    }), 'notification-service', true);
    expect(direct.sanitizedEndpoint).toBe('amqps://broker.example:5671/vhost');
    expect(direct.sanitizedEndpoint).not.toContain('strong-password');
    expect(direct.socketOptions.connectionOptions).toEqual(expect.objectContaining({ rejectUnauthorized: true, servername: 'broker.example' }));

    const split = resolveRabbitMqConfig(source({
      RABBITMQ_HOST: 'rabbit', RABBITMQ_PORT: '5671', RABBITMQ_USERNAME: 'service',
      RABBITMQ_PASSWORD: 'password', RABBITMQ_VHOST: 'oudelaa', RABBITMQ_TLS_ENABLED: 'true',
    }), 'gateway', false);
    expect(split.url).toBe('amqps://service:password@rabbit:5671/oudelaa');

    const urlWithSeparateCredentials = resolveRabbitMqConfig(source({
      RABBITMQ_URL: 'amqps://rabbit:5671/oudelaa', RABBITMQ_USERNAME: 'service',
      RABBITMQ_PASSWORD: 'password',
    }), 'gateway', false);
    expect(urlWithSeparateCredentials.url).toBe('amqps://service:password@rabbit:5671/oudelaa');
  });

  it('requires client certificate and key as a pair', () => {
    expect(() => resolveRabbitMqConfig(source({
      RABBITMQ_URL: 'amqps://service:password@rabbit/vhost',
      RABBITMQ_CLIENT_CERT_BASE64: Buffer.from('cert').toString('base64'),
    }), 'gateway', false)).toThrow('configured together');
  });
});
