const path = require('path')
const Koa = require('koa')
const app = new Koa()
const onerror = require('koa-onerror')
const static = require('koa-static')
const logger = require('koa-logger')
const c2k = require('koa-connect')
const {createProxyMiddleware} = require('http-proxy-middleware')
const NodeDocker = require('@tuia/node-docker')
const Eurekaclient = require('eureka-client-ts').default
const router = require('koa-router')()
const history = require('connect-history-api-fallback');
const fs = require('fs')

// error handler
onerror(app)

app.use(
  logger((str, args) => {
    !str.includes('/monitor/check') && console.log(str)
  })
)

// 用于中台确认应用是否运行正常
router.get('/monitor/check', function (ctx, next) {
  ctx.body = 'ok'
})
const middleHistory = () => {
  const middleware = history();
  return async (ctx, next)=> {
    middleware(ctx, null, () => {});
    await next();
  };
};
app.use(middleHistory());
app.use(static(path.join(__dirname, './dist')))

// app.use(c2k(createProxyMiddleware('/manager',{
//   changeOrigin: true,
//   logLevel: 'debug',
//   router(req) {
//     return 'https://mall.jiliang666.com'
//   }}))
// )

app.use(router.routes())

const dockerApp = new NodeDocker({
  app,
  appType: 'koa',
  port: 3000,
})

dockerApp.startServer().then(() => {
  const client = new Eurekaclient({
    port: 3000,
    appName: 'TUIA-ROBOT-MANAGER-NODE',
    services: [
    ],
  })

    ; (async () => {
      await client.start()
      global['eureka'] = client
    })()
})

module.exports = app
