const firstName = _req.getString("firstname");
const lastName = _req.getString("lastname");
const email = _req.getString("email");
const username = _req.getString("username");
const password = _req.getString("password");
const cityUid = _req.getString("city_uid");

const dbCidade = _db.get("cidade", cityUid);
const emailExists = _user.firstByMail(email);
const usernameExists = _user.firstByUser(username);

if (dbCidade === null) {
  _header.status(409);
  _out.json(_val.map().set("error", true).set("message", "city-not-found"));
} else if (emailExists !== null) {
  _out.json(_val.map().set("result", false).set("error", "email-exists"));
} else if (usernameExists !== null) {
  _out.json(_val.map().set("result", false).set("error", "user-exists"));
} else {
  const group = _group.firstByCode("user");
  const user_id = _user.create(
    _val
      .map()
      .set("name", `${firstName} ${lastName}`)
      .set("user", username)
      .set("pass", password)
      .set("mail", email)
      .set("group_id", group.getInt("id"))
  );
  _db.insertIfNotExists(
    "pessoa",
    _val
      .map()
      .set("nome", firstName)
      .set("sobrenome", lastName)
      .set("email", email)
      .set("cidade_id", dbCidade.getInt("id"))
      .set("usuario_id", user_id)
  );
  _out.json(_val.map().set("result", true));
}
