/* eslint-disable no-useless-escape */
const axios = require("axios");
const log = require("../utils/logs.utils");

const issueLabels = {
  bug: 120,
  enhancement: 122,
  question: 125,
  "user-support": 152,
  "web-user": 153,
};

async function processor(data) {
  log.out("issueService.processor: Issue received", "info");
  console.log(data); // TEMPORARY MEASURE
  let out = {};
  out.labels = [issueLabels[data?.label] || 0, issueLabels["web-user"]];
  out.title = data?.subject.replace(/<[^>]+>|[\*\$]/g, "");
  out.body = data?.msg.replace(/<[^>]+>|[\*\$]/g, "");
  return await sendToGitea(out);
}

async function sendToGitea(body) {
  let key = process.env.OWL_GIT_ISSUEBOT;
  let url = process.env.OWL_GIT_APIENDPOINT;
  let opts = {
    headers: {
      Authorization: key,
    },
  };
  var res = await axios.post(url, body, opts);
  /* Need to read the output from the POST and pass the result upwards to the
     client.*/
  if (res.status == 201) {
    log.out("issueService.sendToGitea: Issue sent to Gitea", "info");
    return { status: res.status, message: "issue created" };
  } else {
    log.out(`issueService.sendToGitea: Fail to send issue: ${res.body}`, "err");
    return { status: res.status, message: "issue not created" };
  }
}

module.exports = {
  processor,
};
