import { assertRedisConfig } from './check-redis-config';

const VALID = 'redis://default:s3cret@redis.example:6379/0';

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

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

  it('parses a well-formed redis URL', () => {
    process.env['REDIS_URL'] = VALID;
    expect(assertRedisConfig()).toEqual({
      url: VALID,
      host: 'redis.example',
      port: 6379,
    });
  });

  it('defaults the port to 6379 when the URL omits it', () => {
    process.env['REDIS_URL'] = 'redis://default:s3cret@redis.example/0';
    expect(assertRedisConfig().port).toBe(6379);
  });

  it('accepts rediss:// for TLS-wrapped connections (future prod)', () => {
    process.env['REDIS_URL'] = 'rediss://default:s3cret@redis.example:6380/0';
    const config = assertRedisConfig();
    expect(config.host).toBe('redis.example');
    expect(config.port).toBe(6380);
  });

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

  it('throws when REDIS_URL is not a valid URL', () => {
    process.env['REDIS_URL'] = 'not-a-url';
    expect(() => assertRedisConfig()).toThrow(/not a valid URL/);
  });

  it('throws when scheme is neither redis: nor rediss:', () => {
    process.env['REDIS_URL'] = 'http://default:s3cret@redis.example:6379/0';
    expect(() => assertRedisConfig()).toThrow(/must use the "redis:\/\/" or "rediss:\/\/" scheme/);
  });

  it('throws when password is absent (local stack requires one)', () => {
    process.env['REDIS_URL'] = 'redis://redis.example:6379/0';
    expect(() => assertRedisConfig()).toThrow(/no password/);
  });

  it('throws when password is still the .env.example placeholder', () => {
    process.env['REDIS_URL'] = 'redis://default:redis_dev_change_me@redis.example:6379/0';
    expect(() => assertRedisConfig()).toThrow(/placeholder/);
  });
});
