const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const path = require("path");
const compression = require("compression");
var enforce = require("express-sslify");
if (process.env.NODE_ENV !== "production") require("dotenv").config();

const https = require("https");
const fs = require("fs");

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

app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(enforce.HTTPS({ trustProtoHeader: true }));
app.use(cors());

var s3upload = require("./s3upload");
app.post("/sign_s3", s3upload.sign_s3);
app.get("/sign_s3", s3upload.get_s3);
app.post("/delete_s3", s3upload.delete_s3);

var sendEmail = require("./sendemail.js");
app.post("/sendemail", sendEmail.sendEmail);
// app.get("/test", function(req, res) {
//   res.json({ success: true });
// });

if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "client/build")));

  app.get("/service-worker.js", (req, res) => {
    res.sendFile(path.resolve(__dirname, "..", "build", "service-worker.js"));
  });

  app.get("*", function(req, res) {
    res.sendFile(path.join(__dirname, "client/build", "index.html"));
  });
}

if (process.env.NODE_ENV === "production") {
  app.listen(port, error => {
    if (error) throw error;
    console.log("[PRODUCTION] Server running on port " + port);
  });
} else {
  https
    .createServer(
      {
        key: fs.readFileSync("./key.pem"),
        cert: fs.readFileSync("./cert.pem"),
        passphrase: "Wl0d8k@!"
      },
      app
    )
    .listen(port, error => {
      if (error) throw error;
      console.log("[DEV/STAGING] Mock HTTPS Server running on port " + port);
    });
}

// app.listen(port, error => {
//   if (error) throw error;
//   console.log("Server running on port " + port);
// });
