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 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");
const { canvastest } = require("../render/canvas-handler");
const { alertCheck } = require("../alerts/alertcheck");
const updateBodyshopCache = require("../web-sockets/updateBodyshopCache");
const { v4 } = require("uuid");

//Test route to ensure Express is responding.
router.get("/test", eventAuthorizationMiddleware, 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}`);
});

router.get("/test-logs", eventAuthorizationMiddleware, (req, res) => {
  const { logger } = req;
  // // Test 1: Log with a message that exceeds the size limit, triggering an upload to S3.
  const largeMessage = "A".repeat(256 * 1024 + 1); // Message larger than the log size limit
  logger.log(largeMessage, "error", "user123", null, { detail: "large log entry" });

  // Test 2: Log with a message that is within the size limit, should log directly using winston.
  const smallMessage = "A small log message";
  logger.log(smallMessage, "info", "user123", null, { detail: "small log entry" });

  // Test 3: Log with the `upload` flag set to `true`, forcing the log to be uploaded to S3.
  logger.log(
    "This log will be uploaded to S3 regardless of size",
    "warning",
    "user123",
    null,
    { detail: "upload log" },
    true
  );

  // Test 4: Log with a message that doesn't exceed the size limit and doesn't require an upload.
  logger.log("Normal log entry", "debug", "user123", { id: 4 }, { detail: "normal log entry" });

  return res.status(500).send("Logs tested.");
});

router.get("/wstest", eventAuthorizationMiddleware, (req, res) => {
  const { ioRedis } = req;
  ioRedis.to(`bodyshop-broadcast-room:bfec8c8c-b7f1-49e0-be4c-524455f4e582`).emit("new-message-summary", {
    isoutbound: true,
    conversationId: "2b44d692-a9e4-4ed4-9c6b-7d8b0c44a0f6",
    msid: "SM5d053957bc0da29399b768c23bffcc0f",
    summary: true
  });

  // TODO: Do we need to add more content here?
  ioRedis
    .to(`bodyshop-conversation-room:bfec8c8c-b7f1-49e0-be4c-524455f4e582:2b44d692-a9e4-4ed4-9c6b-7d8b0c44a0f6`)
    .emit("new-message-detailed", {
      //
      // msid: "SMbbd7703a898fef7f2c07c148ade8a6cd",
      // text: "test2",
      // conversationid: "2b44d692-a9e4-4ed4-9c6b-7d8b0c44a0f6",
      // isoutbound: true,
      // userid: "patrick@imex.dev",
      // image: false,
      // image_path: [],
      newMessage: {
        conversation: {
          id: v4(),
          archived: false,
          bodyshop: {
            id: "bfec8c8c-b7f1-49e0-be4c-524455f4e582",
            imexshopid: "APPLE"
          },
          created_at: "2024-11-19T19:46:38.984633+00:00",
          updated_at: "2024-11-19T22:40:48.346875+00:00",
          unreadcnt: 0,
          phone_num: "+16138676684"
        },
        conversationid: "2b44d692-a9e4-4ed4-9c6b-7d8b0c44a0f6",
        created_at: "2024-11-19T22:40:48.346875+00:00",
        id: "68604ea9-c411-43ec-ab83-899868e58819",
        image_path: [],
        image: false,
        isoutbound: true,
        msid: "SMbbd7703a898fef7f2c07c148ade8a6cd",
        read: false,
        text: `This is a test ${Math.round(Math.random() * 100)}`,
        updated_at: "2024-11-19T22:40:48.346875+00:00",
        status: "posted",
        userid: "patrick@imex.dev"
      },
      conversationId: "2b44d692-a9e4-4ed4-9c6b-7d8b0c44a0f6",
      summary: false
    }); // TODO: Do we need to add more content here?

  return res.status(500).send("Logs tested.");
});

// 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", express.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);

// Canvas Test
router.post("/canvastest", validateFirebaseIdTokenMiddleware, canvastest);

// Alert Check
router.post("/alertcheck", eventAuthorizationMiddleware, alertCheck);

//EMS Upload
router.post("/emsupload", validateFirebaseIdTokenMiddleware, data.emsUpload);

// Redis Cache Routes
router.post("/bodyshop-cache", eventAuthorizationMiddleware, updateBodyshopCache);


module.exports = router;
