import { assertDatabaseUrl } from './check-database-url';

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

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

  it('passes for a well-formed URL with a URL-safe password', () => {
    process.env['DATABASE_URL'] = 'postgresql://user:safePass123@localhost:5432/db?schema=public';
    expect(() => assertDatabaseUrl()).not.toThrow();
  });

  it('passes for a password whose special chars are URL-encoded', () => {
    // Original password contained `@` and `#` — encoded as %40 and %23.
    process.env['DATABASE_URL'] = 'postgresql://user:p%40ss%23word@localhost:5432/db';
    expect(() => assertDatabaseUrl()).not.toThrow();
  });

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

  it('throws when DATABASE_URL has the wrong scheme', () => {
    process.env['DATABASE_URL'] = 'mysql://user:pass@localhost/db';
    expect(() => assertDatabaseUrl()).toThrow(/postgresql:/);
  });

  it('throws when the password contains a literal @ (multiple @ in URL)', () => {
    process.env['DATABASE_URL'] = 'postgresql://user:p@ss@localhost:5432/db';
    expect(() => assertDatabaseUrl()).toThrow(/URL-encoding/);
  });

  it('throws on a fundamentally malformed URL', () => {
    process.env['DATABASE_URL'] = 'not a url at all';
    expect(() => assertDatabaseUrl()).toThrow(/not a valid URL/);
  });
});
