import { Hono } from 'hono'
import { readdirSync } from 'fs'
import { join } from 'path'

const port = process.env.PORT ?? '3100'
const app = new Hono()

app.get('/:file', async c => {
  const file = c.req.param('file') ?? ''
  const fileName = (file).replace('.', '')
  const path = join(process.env.PWD ?? '.', `/src/${fileName}.tsx`)

  if (!(await Bun.file(path).exists()))
    return c.text('404 Not Found', 404)

  const page = await import(path + `?t=${Date.now()}`)
  return c.html(<><h1>{file}</h1><page.Test req={c.req} /></>)
})

app.get('/', c => {
  return c.html(<>
    <h1>Test Files</h1>
    <ul style='font-size:150%'>{testFiles().map(x => <li><a href={`/${x}`}>{x}</a></li>)}</ul>
  </>)
})

function testFiles(): string[] {
  return readdirSync('./test')
    .filter(x => x.endsWith('.tsx') && !x.startsWith('server'))
    .map(x => x.replace('.tsx', ''))
    .sort()
}

export default {
  fetch: app.fetch,
  port
}