const Koa = require('koa')
const Router = require('koa-router')
const cors = require('@koa/cors')
const bodyParser = require('koa-bodyparser')
const path = require('path')

const app = new Koa()
const router = new Router()

app.use(cors({
  origin: '*',
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization']
}))

app.use(bodyParser({
  jsonLimit: '10mb',
  formLimit: '10mb'
}))

app.use(require('koa-static')(path.join(__dirname, 'public')))

const errorHandler = async (ctx, next) => {
  try {
    await next()
    if (ctx.status === 404) {
      ctx.body = {
        code: 404,
        message: '接口不存在'
      }
    }
  } catch (error) {
    console.error('Server error:', error)
    ctx.status = error.status || 500
    ctx.body = {
      code: ctx.status,
      message: process.env.NODE_ENV === 'production' ? '服务器内部错误' : error.message
    }
  }
}

app.use(errorHandler)

const orderRoutes = require('./routes/orders')
const categoryRoutes = require('./routes/categories')
const goodsRoutes = require('./routes/goods')
const userRoutes = require('./routes/users')
const uploadRoutes = require('./routes/upload')
const stockRoutes = require('./routes/stock')

router.use('/api/orders', orderRoutes)
router.use('/api/categories', categoryRoutes)
router.use('/api/goods', goodsRoutes)
router.use('/api/users', userRoutes)
router.use('/api/upload', uploadRoutes)
router.use('/api/stock', stockRoutes)

app.use(router.routes())
app.use(router.allowedMethods())

const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`)
})