const express = require('express');
const path = require('path');
const app = express();
const bodyParser = require('body-parser'); // enables use of body parser - body parser helps get data entered from a form (via req.body)
const subRoutes = require('./routes/subs');
const adminRoutes = require('./routes/admin');
const authRoutes = require('./routes/auth');
const mongoConnect = require('./util/database').mongoConnect;
let mailActivator = require('./util/nodemailer'); // activates nodemailer.js
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session); // session argument from express-session

const store = new MongoDBStore({
	uri: 'mongodb+srv://emdbadmin:emdbauto@empool-3klmr.mongodb.net/subscribers',
	collection: 'sessions'
});

app.set('view engine', 'ejs'); // use EJS templating engine
app.set('views', 'views'); // views located here

app.use(bodyParser.urlencoded({
	extended: false
})); // parses text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST) and exposes the resulting object (containing the keys and values) on req.body)
app.use(bodyParser.json()); // for JSON post API requests

app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
	secret: "my secret",
	resave: false,
	saveUninitialized: false,
	store: store
}));

app.use((req, res, next) => {
	console.log('This demo middleware will always run...');
	console.log('req.get("host")', req.get("host"));
	res.setHeader('Access-Control-Allow-Origin', '*');
	res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT');
	res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
	next();
});

app.use(subRoutes);
app.use(authRoutes);
app.use(adminRoutes);

//app.listen(3000);
mongoConnect(() => {
	app.listen(process.env.PORT || 3000);
});
console.log('App running successfully...');