const Koa = require('koa')
const path = require('path')
const url = require('url')
const swaggerGenerator = require('@mtfos/swagger-generator')
const { copyObject } = require('src/utils/index.js')

const app = new Koa()
const config = require('src/config/index.js')

// @ts-ignore
app.proxy = true

// const server = app.listen(config.server.port, () => {
//   console.log(`server start on port ${server.address().port}`); // eslint-disable-line
// });

// load middleware module
const koaLogger = require('koa-logger')
const koaCors = require('@koa/cors')
const koaBody = require('koa-body')
const koaMount = require('koa-mount')
const koaStatic = require('koa-static')
const rootRouter = require('src/routes/index.js')

const packageJSON = require('./package.json')

let swaggerDoc = null;
// generate swagger document
(async () => {
  const swaggerSpec = {
    swaggerDefinition: {
      info: {
        description: 'KeyCloak OAuth Demo Server',
        title: 'KeyCloak',
        version: packageJSON.version
      },
      host: new url.URL(config.server.url).host,
      basePath: '',
      produces: ['application/json'],
      schemes: ['http', 'https'],
      securityDefinitions: {
        JWT: {
          type: 'apiKey',
          in: 'header',
          name: 'Authorization',
          description: 'Bearer token'
        }
      }
    },
    basedir: __dirname,
    files: ['./routes/**/*.js']
  }
  swaggerDoc = await swaggerGenerator.generateSpec(swaggerSpec)
})().catch(err => {
  console.error('[Error] Generate swagger doc failed, ', err)
  process.exit(1)
})

// production 不掛上swagger ui
if (process.env.NODE_ENV !== 'production') {
  app.use(koaMount('/api-docs/', koaStatic(path.resolve(__dirname, 'public', 'swagger-ui'), { index: 'index.html' })))
  rootRouter.get('/api-docs', async c => {
    if (!/\/$/.test(c.url)) c.redirect(`${c.url}/`)
  })
}

// set swagger doc route
rootRouter.get('/api-docs.json', async c => {
  c.type = 'application/json'
  const spec = copyObject(swaggerDoc || {})

  if (c.protocol === 'https') {
    spec.schemes = ['https']
  }

  c.body = spec
})

app.use(koaLogger())
app.use(
  koaCors({
    credentials: true,
    // allow all origin
    origin: ctx => ctx.get('origin')
  })
)
app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 100 * 1024 * 1024 // 100 mb
    }
  })
)
app.use(koaMount('/', koaStatic(path.resolve(__dirname, 'public', 'html'))))
app.use(rootRouter.allowedMethods())
app.use(rootRouter.routes())

module.exports = app
