const express = require("express");
const router = express.Router();
const logger = require("../../server/utils/logger");
const sendEmail = require("../email/sendemail");
const data = require("../data/data");
const bodyParser = require("body-parser");
const ioevent = require("../ioevent/ioevent");
const taskHandler = require("../tasks/tasks");
const os = require("../opensearch/os-handler");
const eventAuthorizationMiddleware = require("../middleware/eventAuthorizationMIddleware");
const validateFirebaseIdTokenMiddleware = require("../middleware/validateFirebaseIdTokenMiddleware");
const withUserGraphQLClientMiddleware = require("../middleware/withUserGraphQLClientMiddleware");
const { taskAssignedEmail, tasksRemindEmail } = require("../email/tasksEmails");

//Test route to ensure Express is responding.
router.get("/test", async function (req, res) {
  const commit = require("child_process").execSync("git rev-parse --short HEAD");
  // console.log(app.get('trust proxy'));
  // console.log("remoteAddress", req.socket.remoteAddress);
  // console.log("X-Forwarded-For", req.header('x-forwarded-for'));
  logger.log("test-api-status", "DEBUG", "api", { commit });
  // sendEmail.sendServerEmail({
  //   subject: `API Check - ${process.env.NODE_ENV}`,
  //   text: `Server API check has come in. Remote IP: ${req.socket.remoteAddress}, X-Forwarded-For: ${req.header('x-forwarded-for')}`,
  // });
  sendEmail.sendServerEmail({
    subject: `API Check - ${process.env.NODE_ENV}`,
    text: `Server API check has come in.`
  });
  res.status(200).send(`OK - ${commit}`);
});

// Search
router.post("/search", validateFirebaseIdTokenMiddleware, withUserGraphQLClientMiddleware, os.search);
router.post("/opensearch", eventAuthorizationMiddleware, os.handler);

// IO Events
router.post("/ioevent", ioevent.default);

// Email
router.post("/sendemail", validateFirebaseIdTokenMiddleware, sendEmail.sendEmail);
router.post("/emailbounce", bodyParser.text(), sendEmail.emailBounce);

// Tasks Email Handler
router.post("/tasks-assigned-handler", eventAuthorizationMiddleware, taskAssignedEmail);
router.post("/tasks-remind-handler", eventAuthorizationMiddleware, tasksRemindEmail);

// Handlers
router.post("/record-handler/arms", data.arms);
router.post("/taskHandler", validateFirebaseIdTokenMiddleware, taskHandler.taskHandler);

module.exports = router;
