var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');

// import routes
var indexRouter = require('./index');
var usersRouter = require('./users');
const snowflakeRouter = require('./snowflake');
const swaggerRouter = require('./swagger');

var app = express();

const getAPIs = () => {
  const newApp = express()

  newApp.set('views', path.join(__dirname, 'views'));
  newApp.set('view engine', 'jade');
  newApp.use(bodyParser.json({ limit: '50mb', extended: true }));
  newApp.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))
  newApp.use(logger('dev'));
  newApp.use(express.json());
  newApp.use(express.urlencoded({ extended: false }));
  newApp.use(cookieParser());
  newApp.use(express.static(path.join(__dirname, 'public')));

  // wire up routes
  newApp.use('/', indexRouter);
  newApp.use('/users', usersRouter);
  newApp.use('/snowflake', snowflakeRouter);
  newApp.use('/api-docs', swaggerRouter);
  return newApp;
}
const startStore = () => {
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(bodyParser.json({limit: '50mb', extended: true}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// wire up routes
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/snowflake', snowflakeRouter);
app.use('/api-docs', swaggerRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
}

startStore()
module.exports = {app,startStore, getAPIs}
