import { User } from "../../lib/models.js";
import logging from '../../lib/logging.js';
import assert from 'assert';
import { API } from '../../lib/api.js';

const log = logging.create("/api/user/profile.js");

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

export const post = async (req, res) => {
  const api = new API(req, res);
  let user = api.validate(rules);

  try {
    if(!user._valid) {
      return api.validation_error(res, user);
    } else {
      api.clean_form(user, rules, ["password_repeat"]);

      user.password = User.encrypt_password(user.password);

      let result = await User.update({id: req.user.id}, user);
      assert(result !== undefined, "Severe database error.");

      return api.reply(200, { message: "OK" });
    }
  } catch (error) {
    log.error(error);
    return api.error(500, "Internal Server Error");
  }
}

post.authenticated = true;
