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

const userEmailExists = _user.firstByMail(email)
const usernameExists = _user.firstByUser(username)

const dbCidade = _db.get("cidade", city_uid)

if (userEmailExists) {
    _header.status(409)
    _out.json(
        _val.map()
            .set("result", false)
            .set("error", "email-exists")
    )
} else if (usernameExists) {
    _header.status(409)
    _out.json(
        _val.map()
            .set("result", false)
            .set("error", "username-exists")
    )
} else if (dbCidade == null) {
    _header.status(409)
    _out.json(
        _val.map()
            .set("result", false)
            .set("error", "city-not-found")
    )
} else {
    const dbNetunoGroup = _group.firstByCode("utilizador")

    const user_id = _user.create(
        _val.map()
            .set("name", name)
            .set("mail", email)
            .set("user", username)
            .set("pass", password)
            .set("group_id", dbNetunoGroup.getInt("id"))
    )

    _db.insertIfNotExists(
        "pessoa",
        _val.map()
            .set("nome", name)
            .set("apelido", surname)
            .set("email", email)
            .set("cidade_id", dbCidade.getInt("id"))
            .set("utilizador_id", user_id)
    )

    _out.json(
        _val.map()
            .set("result", true)
    )
}
