import "./utils/env";
import express, { Request, Response, NextFunction, Application } from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import expressSession from "express-session";
import authRoute from "./routes/auth";
import newsRoute from "./routes/news";

mongoose
  .connect("mongodb://localhost:27017/bodysch", {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log("Connected to database");
  })
  .catch(err => {
    console.log(
      "MongoDB connection error. Please make sure MongoDB is running. " + err
    );
    // process.exit();
  });

const app: Application = express();

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(
  expressSession({
    secret: process.env.SESSION_SECRET || "alma",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
  })
);
app.use((req: Request, res: Response, next: NextFunction) => {
  res.data = {};
  next();
});

app.get("/", (req: Request, res: Response) => {
  let message = "World!";
  if (req.session!.user) message = req.session!.user!.sn || "World!";
  res.send("Hello " + message);
});

// Register routes
authRoute(app);

// Register routes
newsRoute(app);

app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  res.status(500).send("Houston, we have a problem!");

  //Flush out the stack to the console
  console.error(err.stack);
});

app.listen(8000, () => console.log(`Example app listening on port 8000!`));