const client = require("../graphql-client/graphql-client").client;
const emailer = require("../email/sendemail");
const moment = require("moment-timezone");
const converter = require("json-2-csv");
const logger = require("../utils/logger");
const queries = require("../graphql-client/queries");
const InstanceMgr = require("../utils/instanceMgr").default;

exports.default = async (req, res) => {
  try {
    logger.log("usage-report-email-start", "debug", req?.user?.email, null, {});

    if (InstanceMgr({ rome: false, imex: true })) {
      //Disable for ImEX at the moment.
      res.sendStatus(403);
      logger.log("usage-report-email-forbidden", "warn", req?.user?.email, null, {});
      return;
    }

    if (process.env.NODE_ENV !== "production") {
      res.sendStatus(403);
      return;
    }
    // Validate using autohouse token header.
    if (req.headers["x-imex-auth"] !== process.env.AUTOHOUSE_AUTH_TOKEN) {
      res.sendStatus(401);
      logger.log("usage-report-email-forbidden", "warn", req?.user?.email, null, {});
      return;
    }

    //Query the usage data.
    const queryResults = await client.request(queries.STATUS_UPDATE, {
      today: moment().startOf("day").subtract(7, "days"),
      period: moment().subtract(365, "days").startOf("day")
    });

    //Massage the data.
    const shopList = queryResults.bodyshops.map((shop) => ({
      "Shop Name": shop.shopname,
      "Days Since Creation": moment().diff(moment(shop.created_at), "days"),
      "Jobs Created": shop.jobs_created.aggregate.count,
      "Jobs Updated": shop.jobs_updated.aggregate.count,
      "Owners Created": shop.owners_created.aggregate.count,
      "Owners Updated": shop.owners_updated.aggregate.count,
      "Vehicles Created": shop.vehicles_created.aggregate.count,
      "Vehicles Updated": shop.vehicles_updated.aggregate.count,
      "Tasks Created": shop.tasks_created.aggregate.count,
      "Tasks Updated": shop.tasks_updated.aggregate.count
    }));

    const csv = converter.json2csv(shopList, { emptyFieldValue: "" });
    emailer
      .sendTaskEmail({
        to: [
          "patrick.fic@convenient-brands.com",
          "bradley.rhoades@convenient-brands.com",
          "jrome@rometech.com",
          "ivana@imexsystems.ca",
          "support@imexsystems.ca",
          "sarah@rometech.com"
        ],
        subject: `RO Usage Report - ${moment().format("MM/DD/YYYY")}`,
        text: `
Usage Report for ${moment().format("MM/DD/YYYY")} for Rome Online Customers. 
        
Notes:
  - Days Since Creation: The number of days since the shop was created. Only shops created in the last 365 days are included.
  - Updated values should be higher than created values.
  - Counts are inclusive of the last 7 days of data.
        `,
        attachments: [{ filename: `RO Usage Report ${moment().format("MM/DD/YYYY")}.csv`, content: csv }]
      })
      .then(() => {
        logger.log("usage-report-email-success", "debug", req?.user?.email, null, {
          csv
        });
      })
      .catch((error) => {
        logger.log("usage-report-email-send-error", "ERROR", req?.user?.email, null, {
          error: error.message,
          stack: error.stack
        });
      });
    res.sendStatus(200);
    return;
  } catch (error) {
    logger.log("usage-report-email-error", "ERROR", req?.user?.email, null, {
      error: error.message,
      stack: error.stack
    });
    res.status(500).json({ error: error.message, stack: error.stack });
  }
};
