import { User, Site, } from "../lib/models.js";
import * as queues from "../lib/queues.js";
import { defer, API } from "../lib/api.js";
import { register_enabled } from "../client/config.js";

const rules = User.validation({
  email: '',
  full_name: '',
  initials: 'required|alpha|max:3',
  password_repeat: 'required|same:password',
  password: '',
  tos_agree: 'required|boolean|accepted',
})

export const post = async (req, res) => {
  const api = new API(req, res);

  if(!register_enabled) {
    return api.error(401, {_errors: { main: "Registration is disabled."}});
  } else {
    const form = api.validate(rules);

    if(!form._valid) {
      return api.validation_error(res, form);
    } else {
      api.clean_form(form, rules);

      // register the user with this payment
      let good = await User.register({
        email: form.email,
        full_name: form.full_name,
        initials: form.initials,
        password: form.password,
        password_repeat: form.password_repeat,
      });

      // confirm the user was saved
      if(!good) {
        return api.error(400, {_errors: {main: "Failed to register user. Do you already have an account?"}});
      } else {
        const wait_for = defer();

        Site.increment("registered_count", 1);

        delete good.password;

        queues.send_registration(good);

        // NOTE: we have to use a defer here because
        // this function returns which finalizes headers
        // in express, but we have to wait for the passport
        // login system to do its headers
        api.req.login(good, (err) => {
          if(err) {
            console.error(err, "login error in register");
            wait_for.reject(err);
            return false;
          } else {
            api.reply(200, {message: "OK"});
            wait_for.resolve("YES");
            return true;
          }
        });

        await wait_for;
        return true; // mostly just here to keep eslint happy
      }
    }
  }
}
