const Dinero = require("dinero.js");
const queries = require("../graphql-client/queries");
const logger = require("../utils/logger");
const { job } = require("../scheduling/scheduling-job");
const _ = require("lodash");

// Dinero.defaultCurrency = "USD";
// Dinero.globalLocale = "en-CA";

exports.partsScan = async function (req, res) {
  const { jobid } = req.body;

  const BearerToken = req.BearerToken;
  const client = req.userGraphQLClient;

  logger.log("job-parts-scan", "DEBUG", req.user?.email, jobid, null);

  try {
    //Query all jobline data using the user's authorization.
    const data = await client.setHeaders({ Authorization: BearerToken }).request(queries.QUERY_PARTS_SCAN, {
      id: jobid
    });

    //Create RegExps once for better performance.
    const IdsToMarkCritical = [];
    const RegExpressions = data.jobs_by_pk.bodyshop.md_parts_scan.map((r) => new RegExp(r.expression, r.flags));

    //Check each line against each regex rule.
    data.jobs_by_pk.joblines.forEach((jobline) => {
      RegExpressions.forEach((rExp) => {
        if (jobline.line_desc.match(rExp)) {
          IdsToMarkCritical.push(jobline);
        }
      });
    });

    const result = await client.setHeaders({ Authorization: BearerToken }).request(queries.UPDATE_PARTS_CRITICAL, {
      IdsToMarkCritical: _.uniqBy(IdsToMarkCritical, "id").map((i) => i.id),
      jobid: jobid
    });

    res.status(200).json(result);
  } catch (error) {
    logger.log("job-parts-scan-error", "ERROR", req.user.email, jobid, {
      jobid,
      error
    });
    res.status(400).json(JSON.stringify(error));
  }
};
