/**
 * CORS middleware tests — verifies the origin-pinned allowlist echoes approved
 * origins (including the www origins required for signup) and omits unknown ones.
 */
import { describe, it, expect } from 'vitest'
import { Hono } from 'hono'
import { corsMiddleware } from '../src/middleware/cors'

function appWithCors() {
  const app = new Hono()
  app.use('*', corsMiddleware)
  app.get('/ping', (c) => c.text('ok'))
  return app
}

describe('corsMiddleware allowlist', () => {
  it('echoes the dev www origin (required for signup)', async () => {
    const res = await appWithCors().request('/ping', {
      headers: { Origin: 'https://dev.zync.is' },
    })
    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('https://dev.zync.is')
    expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true')
  })

  it('echoes the prod www origin', async () => {
    const res = await appWithCors().request('/ping', {
      headers: { Origin: 'https://zync.is' },
    })
    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('https://zync.is')
  })

  it('adds CORS headers when a route returns a raw response', async () => {
    const app = new Hono()
    app.use('*', corsMiddleware)
    app.get('/raw', () => new Response('ok'))

    const res = await app.request('/raw', {
      headers: { Origin: 'https://dev.zync.is' },
    })

    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('https://dev.zync.is')
    expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true')
  })

  it('does not echo an unknown origin', async () => {
    const res = await appWithCors().request('/ping', {
      headers: { Origin: 'https://evil.example.com' },
    })
    expect(res.headers.get('Access-Control-Allow-Origin')).toBeNull()
  })
})
