const express = require("express");
const session = require("express-session");
//const MongoStore = require("connect-mongo");
const path = require("path");
const bodyParser = require("body-parser");
const cors = require("cors");
const promisify = require("es6-promisify");
const fileUpload = require("express-fileupload");

const apiRouterAuth = require("./routes/auth");
const apiRouterShopperrB2C = require("./routes/shopperrb2c");
const apiRouterShopperrB2B = require("./routes/shopperrb2b");
const apiRouterShopperrDS = require("./routes/shopperrds");
const apiRouterWebcron = require("./routes/webcron");
const apiRouterAdmin = require("./routes/admin");
const apiRouterWebService = require("./routes/apiWebService");
const apiRouterWms = require("./routes/wms");
const apiRouterLegacy = require("./routes/legacy");
const errorHandlers = require("./handlers/errorHandlers");
const apiBilling = require("./routes/apiBilling");
const apiSolr = require("./routes/apiSolr");
const apiItadmin = require("./routes/itadmin");
const pgRoute = require("./routes/pgRoute");

require("dotenv").config({ path: ".env" });

// create our Express app
const app = express();
app.use(cors());
app.use(cors({ origin: 'https://dropship.shopperr.in' }));
app.use(express.json({ limit: "100mb" }));
app.use(fileUpload());
// serves up static files from the public folder. Anything in public/ will just be served up as the file it is
app.use(express.static(path.join(__dirname, "public")));

// Takes the raw requests and turns them into usable properties on req.body
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.urlencoded({
  limit: "98mb",
  extended: false
}));
app.use(bodyParser.json({limit: "98mb"}));

// Sessions allow us to Contact data on visitors from request to request
// This keeps admins logged in and allows us to send flash messages
app.use(
  session({
    secret: process.env.SECRET,
    key: process.env.KEY,
    resave: false,
    saveUninitialized: false,
   // store: MongoStore.create({ mongoUrl: process.env.DATABASE }),
  })
);
 
// pass variables to our templates + all requests
app.use((req, res, next) => {
  res.locals.admin = req.admin || null;
  res.locals.currentPath = req.path;
  next();
});

// promisify some callback based APIs
app.use((req, res, next) => {
  req.login = promisify(req.login, req);
  next();
});

app.use((req, res, next) => {
	bodyParser.json({
		verify: addRawBody,
	})(req, res, (err) => {
		if (err) {
			console.log(err);
			res.sendStatus(400);
			return;
		}
		next();
	});
});

function addRawBody(req, res, buf, encoding) {
	req.rawBody = buf.toString();
}

// Here our API Routes
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Methods", "GET,PATCH,PUT,POST,DELETE");
  res.header("Access-Control-Expose-Headers", "Content-Length");
  res.header(
    "Access-Control-Allow-Headers",
    "Accept, Authorization,x-auth-token, Content-Type, X-Requested-With, Range"
  );
  if (req.method === "OPTIONS") {
    return res.sendStatus(200);
  } else {
    return next();
  }
});
// for development & production don't use this line app.use("/api", apiRouter); , this is just demo login contoller
app.use("/auth", apiRouterAuth);
app.use("/shopperrb2c", apiRouterShopperrB2C);
app.use("/shopperrb2b", apiRouterShopperrB2B);
app.use("/shopperrds", apiRouterShopperrDS);
app.use("/menu", apiRouterShopperrDS);
app.use("/admin", apiRouterAdmin);
app.use("/wms", apiRouterWms);
app.use("/legacy", apiRouterLegacy);
app.use("/api", apiBilling);
app.use("/solr", apiSolr);
app.use("/itadmin", apiItadmin);
app.use("/pg", pgRoute);

app.use("/", apiRouterWebService);

//uncomment line below // app.use("/api", isValidToken, apiRouter);
// app.use("/api", isValidToken, apiRouter);

// If that above routes didnt work, we 404 them and forward to error handler
app.use(errorHandlers.notFound);

// Otherwise this was a really bad error we didn't expect! Shoot eh
if (app.get("env") === "development") {
  /* Development Error Handler - Prints stack trace */
  app.use(errorHandlers.developmentErrors);
}

// production error handler
app.use(errorHandlers.productionErrors);

// done! we export it so we can start the site in start.js
module.exports = app;
