const log = require("../utils/logs.utils");
const auth = require("../utils/auth.utils");
const db = require("./dbAccess.services");
const mail = require("./mail.services");
const clean = require("../utils/sanitizer.utils");
const domains = require("../configs/domains.configs");
const errors = require("../configs/errorCodes.configs");

async function createRegKey(body) {
  log.out("registerServices.createRegKey: Incoming request", "INFO");
  if (body.email) {
    const domain = await clean.getDomainFromEmail(body.email);
    log.out(`registerServices: Registration request from: ${domain}`, "info");
    if (domains.includes(domain)) {
      log.out(
        `registerServices.createRegKey: Key from valid: ${domain}`,
        "info"
      );
      const uuid = await auth.generateKey();
      db.addRegReq(uuid, domain);
      const message = await auth.generateConfirmationEmail(body.email, uuid);
      if (!message) {
        const err = new Error("Message generation error");
        log.out("registerServices.createRegKey: Error generating email", "err");
        log.out(err, "err");
        return 500;
      }
      if ((await mail.send(message)) == true) {
        return { status: 201, message: "email sent" };
      }
      return { status: 500, errorCode: 950, errorMsg: errors[950] };
    }
    return { status: 403, errorCode: 702, errorMsg: errors[702] };
  } else {
    return { status: 400, errorCode: 901, errorMsg: errors[902] };
  }
}

async function regUser(req) {
  // Add input validation
  log.out(`Read UUID: ${req.uuid}`, "dbug");
  log.out(`registrationServices.regUser: Request from: ${req.uuid}`, "info");
  const res = await auth.checkRequest(req.uuid);
  log.out(`registrationServices.regUser: ${JSON.stringify(res)}`, "info");
  if (res.result) {
    const uuid = await auth.generateKey();
    const apiKey = await db.addUser(uuid, res.domain);
    if (apiKey) {
      db.delRegReq(req.uuid);
      return { status: 201, message: "User added", api_key: uuid };
    }
  }
  return { status: 401, errorCode: 703, errorMsg: errors[703] };
}

async function getUser(uuid) {
  log.out("registrationServices: Finding user for given UUID", "dbug");
  try {
    const filter = {
      uuid: uuid,
    };
    const res = await db.query("users", filter, false);
    if (res.length) {
      return res;
    } else {
      return { status: 404, errorCode: 400, errorMsg: errors[400] };
    }
  } catch (err) {
    console.log(err);
    return { status: 500, errorCode: 951, errorMsg: errors[951] };
  }
}

module.exports = {
  regUser,
  createRegKey,
  getUser,
};
