import { readCorsAllowlist } from './check-cors-allowlist';

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

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

  it('parses a single origin', () => {
    process.env['CORS_ALLOWED_ORIGINS'] = 'http://localhost:4200';
    expect(readCorsAllowlist()).toEqual(['http://localhost:4200']);
  });

  it('parses a comma-separated list and trims whitespace', () => {
    process.env['CORS_ALLOWED_ORIGINS'] =
      'http://localhost:4200,  https://portal.apf.example  ,https://admin.portal.apf.example';
    expect(readCorsAllowlist()).toEqual([
      'http://localhost:4200',
      'https://portal.apf.example',
      'https://admin.portal.apf.example',
    ]);
  });

  it('filters out empty entries (trailing commas tolerated)', () => {
    process.env['CORS_ALLOWED_ORIGINS'] = 'http://localhost:4200,';
    expect(readCorsAllowlist()).toEqual(['http://localhost:4200']);
  });

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

  it('throws when the var is the empty string', () => {
    process.env['CORS_ALLOWED_ORIGINS'] = '';
    expect(() => readCorsAllowlist()).toThrow(/CORS_ALLOWED_ORIGINS is not set/);
  });

  it('throws when the parsed list is empty (only commas / whitespace)', () => {
    process.env['CORS_ALLOWED_ORIGINS'] = ' , , ';
    expect(() => readCorsAllowlist()).toThrow(/empty after parsing/);
  });

  it('throws on a non-URL entry', () => {
    process.env['CORS_ALLOWED_ORIGINS'] = 'not-a-url';
    expect(() => readCorsAllowlist()).toThrow(/not a valid URL/);
  });

  it('throws on a non-http(s) scheme', () => {
    process.env['CORS_ALLOWED_ORIGINS'] = 'ftp://files.apf.example';
    expect(() => readCorsAllowlist()).toThrow(/must use http: or https:/);
  });

  it('throws when an entry has a path', () => {
    process.env['CORS_ALLOWED_ORIGINS'] = 'https://portal.apf.example/foo';
    expect(() => readCorsAllowlist()).toThrow(/must be a bare origin/);
  });

  it('accepts a trailing slash by treating it as the root path', () => {
    // `new URL('https://x.example/').pathname` is "/" — we accept
    // that as equivalent to a bare origin.
    process.env['CORS_ALLOWED_ORIGINS'] = 'https://portal.apf.example/';
    expect(readCorsAllowlist()).toEqual(['https://portal.apf.example/']);
  });

  it('throws when an entry has a query string', () => {
    process.env['CORS_ALLOWED_ORIGINS'] = 'https://portal.apf.example?x=1';
    expect(() => readCorsAllowlist()).toThrow(/no query string or fragment/);
  });
});
