import Fastify from 'fastify'
import cookie from '@fastify/cookie'
import cors from '@fastify/cors'
import { initDb } from './db.js'
import { bookingRoutes } from './routes/bookings.js'
import { configRoutes } from './routes/config.js'
import { workforceRoutes } from './routes/workforce.js'

const app = Fastify({ logger: true, trustProxy: true })
const startedAt = Date.now()

await app.register(cookie)
await app.register(cors, { origin: process.env.CORS_ORIGIN || false, credentials: true })

app.get('/health', async () => ({ status: 'healthy', version: process.env.BUILD_VERSION || String(startedAt) }))

await app.register(bookingRoutes)
await app.register(configRoutes)
await app.register(workforceRoutes)

try {
  await initDb()
  await app.listen({ port: 3001, host: '0.0.0.0' })
} catch (err) {
  app.log.error(err)
  process.exit(1)
}
