import express from 'express';
import next from 'next';
import compression from 'compression';
import morgan from 'morgan';
import nextI18NextMiddleware from 'next-i18next/middleware';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';

import nextI18next from '../i18n';
import customRoute from './route';
import apiRoute from './api/index';

const isDev = process.env.ENV !== 'production' && process.env.ENV !== 'preparing';
const app = next({ dev: isDev });
const handle = app.getRequestHandler();

(async () => {
  await app.prepare();
  const server = express();

  server.use(compression());
  server.use(cookieParser());
  if (isDev) {
    server.use(morgan('short'));
  }
  server.use(bodyParser.json());
  server.use(bodyParser.urlencoded({ extended: true }));
  server.use('/api',apiRoute);
  server.use(nextI18NextMiddleware(nextI18next));

  customRoute(server, app, handle);

  server.get('*', (req, res) => {
    handle(req, res);
  });

  await server.listen(4000);
  /* eslint-disable no-console */
  if (isDev) {
    console.log('> Ready on http://localhost:4000');
  } else {
    console.log('> Ready on production');
  }
})();
