require('./app/conf/code.inc')

const Koa = require('koa')
const app = new Koa()
const morgan = require('koa-morgan')
const cookie = require('koa-cookie').default
const bodyParser = require('koa-better-body')
const router = require('./app/router')

// setup the logger
app.use(morgan('dev'))

// setup router
app.use(router.routes())

router.use(cookie())
// setup body parser
app.use(bodyParser({
  multipart: true
}))

app.use(async (ctx, next) => {
  Object.assign(ctx.request.query, ctx.request.fields)

  await next()
  ctx.set('Access-Control-Allow-Origin', ctx.header.origin)
  ctx.set('Access-Control-Allow-Credentials', true)
  ctx.set('Access-Control-Allow-Methods', 'GET,HEAD,PUT,POST,DELETE')
})

// setup listen
const PORT = process.env.PORT || 1024
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}!`)
})

module.exports = app
