import http from "http";
import express from "express";
import cors from "cors";
import morgan from "morgan";
import bodyParser from "body-parser";

import initializeDb from "./db";
import middleware from "./middleware";
import api from "./api";
import config from "config"; //we load the db location from the JSON files

let app = express();
app.server = http.createServer(app);

//don't show the log when it is test
if (process.env.NODE_ENV !== "test") {
  // logger
  app.use(morgan("dev"));
}

// 3rd party middleware
app.use(
  cors({
    exposedHeaders: config.corsHeaders
  })
);

app.use(
  bodyParser.json({
    limit: config.bodyLimit
  })
);

const dbOptions = {
  useMongoClient: true
};
// connect to db
initializeDb(config.dbURI, dbOptions, () => {
  // internal middleware
  app.use(middleware({ config }));

  // api router
  app.use("/api", api({ config }));

  app.server.listen(process.env.PORT || config.port, () => {
    console.log(`Started on port ${app.server.address().port}`);
  });
});

export default app;
