import { test, expect } from 'bun:test';

// origin-validation reads PUBLIC_URL / PUBLIC_BUILD_ENV at module load, so set them before importing.
process.env.PUBLIC_URL = 'https://officer.example.com';
process.env.PUBLIC_BUILD_ENV = 'production';
// Bun loads the host's .env into tests, so an operational kill switch left on there would silently turn
// these assertions into no-ops — which is exactly what ALLOW_ANY_ORIGIN=true did. Pin the escape hatches
// off: this file's whole job is asserting that the checks reject things.
process.env.ALLOW_ANY_ORIGIN = 'false';
process.env.ALLOW_ANY_ORIGIN_MUSIC = 'false';

const { isOriginAllowed } = await import('./origin-validation');

test('accepts the configured origin', () => {
  expect(isOriginAllowed('https://officer.example.com', 'officer.example.com')).toBe(true);
});

test('accepts the Host forwarded by the reverse proxy when there is no Origin', () => {
  expect(isOriginAllowed(undefined, 'officer.example.com')).toBe(true);
});

test('rejects a foreign Origin', () => {
  expect(isOriginAllowed('https://evil.com', 'officer.example.com')).toBe(false);
  expect(isOriginAllowed('https://officer.example.com.evil.com', 'officer.example.com')).toBe(false);
});

// Regression: the Host branch used `configuredOrigin.endsWith(host)`, so any suffix of the origin —
// down to a bare TLD — authenticated as the real host.
test('rejects Hosts that are merely suffixes of the configured origin', () => {
  for (const host of ['com', 'example.com', 'r.example.com', 'ficer.example.com', 'evil.com']) {
    expect(isOriginAllowed(undefined, host)).toBe(false);
  }
});

test('rejects a request carrying neither Origin nor Host', () => {
  expect(isOriginAllowed(undefined, undefined)).toBe(false);
});
