/** @jsxImportSource hono/jsx */
import { Hype } from '@because/hype'
import { PhonePage, stylesToCSS } from '../pages/phone'
import { startup } from './terminal'

const PORT = Number(process.env.PORT) || 3000
const app = new Hype({ layout: false, logging: false })

app.get('/ok', c => c.text('ok'))

app.get('/styles.css', c =>
  c.text(stylesToCSS(), 200, { 'Content-Type': 'text/css; charset=utf-8' })
)

app.get('/', c => c.html(<PhonePage />))

app.get('/ggwave.js', () =>
  new Response(Bun.file(new URL(import.meta.resolve('ggwave/ggwave.js')).pathname), {
    headers: { 'Content-Type': 'application/javascript' },
  })
)

startup(PORT)

async function ensureCerts() {
  const certPath = './certs/cert.pem'
  const keyPath = './certs/key.pem'
  if (await Bun.file(certPath).exists()) return

  const { mkdirSync } = await import('fs')
  mkdirSync('./certs', { recursive: true })
  Bun.spawnSync(['openssl', 'req', '-x509', '-newkey', 'rsa:2048',
    '-keyout', keyPath, '-out', certPath,
    '-days', '365', '-nodes', '-subj', '/CN=localhost'])
}

await ensureCerts()

export default {
  ...app.defaults,
  port: PORT,
  idleTimeout: 255,
  tls: {
    key: Bun.file('./certs/key.pem'),
    cert: Bun.file('./certs/cert.pem'),
  },
}
