import assert from 'node:assert/strict'
import { once } from 'node:events'
import test from 'node:test'

import { createApp } from './app.js'
import { createDefaultRuntimeConfig } from './config/defaults.js'
import { createStartupState } from './startup/state.js'

test('HTTP health route and explicit CORS preflight', async () => {
  const startupState = createStartupState()
  startupState.core.ready = true
  const config = createDefaultRuntimeConfig('/tmp/order-site')
  config.cors.allowedOrigins = ['https://order.example.test']
  const server = createApp({
    startupState,
    isShutdownStarted: () => false,
    config,
  }).listen(0, '127.0.0.1')
  await once(server, 'listening')

  try {
    const address = server.address()
    assert.ok(address && typeof address === 'object')
    const baseUrl = `http://127.0.0.1:${address.port}`
    const health = await fetch(`${baseUrl}/health/live`)
    assert.equal(health.status, 200)
    assert.equal((await health.json()).data.status, 'alive')

    const preflight = await fetch(`${baseUrl}/api/v1/health`, {
      method: 'OPTIONS',
      headers: { Origin: 'https://order.example.test' },
    })
    assert.equal(preflight.status, 204)
    assert.equal(preflight.headers.get('access-control-allow-origin'), 'https://order.example.test')
    assert.equal(preflight.headers.get('vary'), 'Origin')
  } finally {
    server.close()
    await once(server, 'close')
  }
})
