
const name = _req.getString("name")
const surname = _req.getString("surname")
const cityUid = _req.getString("city_uid")
const email = _req.getString("email")
const username = _req.getString("username")
const password = _req.getString("password")

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) {
    _header.status(409)
    _out.json(
        _val.map()
            .set("error", true)
            .set("message", "email-exists")
    )
} else if (usernameExists != null) {
    _header.status(409)
    _out.json(
        _val.map()
            .set("error", true)
            .set("message", "user-exists")
    )
} else {
    const group = _group.firstByCode("user")
    const user_id = _user.create(
        _val.map()
            .set("name", `${name} ${surname}`)
            .set("mail", email)
            .set("user", username)
            .set("pass", password)
            .set("group_id", group.getInt("id"))
    )
    _db.insert(
        'pessoa',
        _val.map()
            .set("nome", name)
            .set("apelido", surname)
            .set("email", email)
            .set("utilizador_id", user_id)
            .set("cidade_id", dbCidade.getInt("id"))
    )
    _log.info("Novo utilizador criado com o id: "+ user_id)
    _out.json(_val.map().set("result", true))
}
