import cors from 'cors'
import express from 'express'
import { setAuthorization } from './utils/headers'
import { getOpenAIClient } from './utils/openai'
import { registerChatRoutes } from './route/chat'
import { registerBasicRoutes } from './route/basic'

const client = getOpenAIClient()
const app = express()
const PORT = 4000

app.use(cors())
app.use(express.json())
// 写一个中间件 如果请求头里面有 authorization 字段 就把他存在 本地中
app.use((req, res, next) => {
  if (req.headers.authorization) {
    setAuthorization(req.headers.authorization)
  }
  next()
})

registerBasicRoutes(app, client)
registerChatRoutes(app, client)
app.use((_req, res) => {
  res.status(404).json({ error: 'not found' })
})

app.listen(PORT, () => {
  console.log(`[server] http://localhost:${PORT}`)
})
