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

import app from './app'

const preflight = (origin: string) =>
  app.request('/health', {
    method: 'OPTIONS',
    headers: {
      Origin: origin,
      'Access-Control-Request-Method': 'GET',
    },
  })

test('allows localhost origins', async () => {
  const res = await preflight('http://localhost:8081')
  expect(res.headers.get('access-control-allow-origin')).toBe(
    'http://localhost:8081',
  )
})

test('allows exp.direct origins', async () => {
  const res = await preflight('https://abc.exp.direct')
  expect(res.headers.get('access-control-allow-origin')).toBe(
    'https://abc.exp.direct',
  )
})

test('rejects localhost-prefixed lookalike hosts', async () => {
  for (const origin of [
    'http://localhost.evil.com',
    'http://localhostevil.com:8081',
    'https://evilexp.direct',
  ]) {
    const res = await preflight(origin)
    expect(res.headers.get('access-control-allow-origin')).toBeNull()
  }
})

test('sets security headers globally', async () => {
  const res = await app.request('/health')
  expect(res.headers.get('x-content-type-options')).toBe('nosniff')
  expect(res.headers.get('x-frame-options')).toBe('SAMEORIGIN')
  expect(res.headers.get('referrer-policy')).toBe('no-referrer')
})

test('omits cors headers without an origin', async () => {
  const res = await app.request('/health')
  expect(res.headers.get('access-control-allow-origin')).toBeNull()
  expect(
    res.headers.get('access-control-allow-credentials'),
  ).toBeNull()
})
