require ('dotenv').config();
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const flash = require("connect-flash");
const MongoStore = require("connect-mongo");
const cookieParser = require('cookie-parser');

const mongoUrl = process.env.MONGODB_URI

const passport = require('passport');
require('./config/passport')(passport);

const app = express();
const PORT = process.env.PORT || 3000;

mongoose.set('strictQuery', true);
mongoose.connect(process.env.MONGODB_URI);
const db = mongoose.connection;
db.on("error", (error) => console.log(error));
db.once("open", () => {
    return console.log("Database Connected");
});

app.use(express.urlencoded({ extended: true}));
app.use(express.json());

app.use(cookieParser());

app.use(
  session({
    secret: process.env.SECRET_KEY,
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create({
      mongoUrl,              // where sessions will be stored
      ttl: 30 * 60,          // 30 minutes in seconds
      autoRemove: "native",  // let MongoDB handle expired cleanup
    }),
    cookie: {
      maxAge: 30 * 60 * 1000, // 30 minutes in ms
    },
    rolling: true,            // refresh session timer on every request
  })
);

app.use(passport.initialize());
app.use(passport.session());

app.use(flash());

// Global variables for messages
app.use(function(req, res, next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    next();
});
  
  
//Style static folder
app.use(express.static(__dirname + '/public'));

app.set('views', __dirname + '/views');


//Template Engine
app.set("view engine", "ejs");
  
//route prefix
app.use('/', require('./routes/router'));
app.use('/admin', require('./routes/admin-router'));

// If no route matches, render 404 page
app.use((req, res) => {
  res.status(404).render("404"); // views/404.ejs
});
  
app.listen(PORT, ()=> {
console.log(`Server started at http://localhost:${PORT}`);
}); 