"use strict";

const config = require("config"),
  { sendVerifyMail } = require("../server/lib/mail");

const basePath = "/" + config.get("basePath").replace(/^\/+/, "").replace(/\/+$/, "") + "/";

const req = {
  hostname: "ketrenos.com",
  protocol: "https",
  data: {
    basePath: (basePath == "//") ? "/" : basePath
  }
};

const app = req.app = {
  get: function(key) {
    return req.data[key];
  },
  set: function(key, value) {
    req.data[key] = value;
    return value;
  }
};

if (config.has("admin.mail") &&
  config.has("smtp.host") &&
  config.has("smtp.sender")) {
  app.set("transporter", require("nodemailer").createTransport({
    host: config.get("smtp.host"),
    pool: true,
    port: config.has("smtp.port") ? config.get("smtp.port") : 25
  }));
} else {
  console.log("SMTP disabled. To enable SMTP, configure admin.mail, smtp.host, and smtp.sender");
}

if (process.argv.length != 3) {
  console.log("usage: node resend UID");
  process.exit(-1);
}

require("../server/db/users").then(function(db) {
  let id = parseInt(process.argv[2]);
  
  return db.sequelize.query("SELECT * FROM users WHERE id=:id", {
    replacements: {
      id: id
    },
    type: db.Sequelize.QueryTypes.SELECT,
    raw: true
  }).then(function(users) {
    if (users.length != 1) {
      console.log("User not found: " + id);
      process.exit(-1);
    }
    return users[0];
  }).then(function(user) {
    return sendVerifyMail(db, req, user);
  }).then(function() {
    process.exit(0);
  }).catch(function(error) {
    console.log("Error sending verification mail: ", error);
  });
});

