import http from 'http'
import express from 'express'
import cors from 'cors'
import { WebSocketServer } from 'ws'
import meetingsRouter from './routes/meetings.js'
import answerSuggestionsRouter from './routes/answerSuggestions.js'
import { runMigrations } from './migrate.js'

const app = express()
app.use(cors())
app.use(express.json({ limit: '2mb' }))

app.get('/api/health', (_req, res) => {
  res.json({ ok: true })
})

app.use('/api/meetings', meetingsRouter)
app.use('/api/answer_suggestions', answerSuggestionsRouter)

const server = http.createServer(app)
const wss = new WebSocketServer({ server })

function broadcast(data: unknown) {
  const payload = JSON.stringify(data)
  for (const client of wss.clients) {
    if (client.readyState === client.OPEN) {
      client.send(payload)
    }
  }
}

app.locals.broadcast = broadcast

wss.on('connection', (socket) => {
  socket.send(JSON.stringify({ type: 'connected' }))
})

const port = Number(process.env.PORT || 4000)

runMigrations()
  .then(() => {
    server.listen(port, () => {
      // eslint-disable-next-line no-console
      console.log(`Server listening on ${port}`)
    })
  })
  .catch((err) => {
    // eslint-disable-next-line no-console
    console.error('Migration failed:', err)
    process.exit(1)
  })
