const bcrypt = require("bcrypt");

async function createUser(
  db,
  first_name,
  last_name,
  username,
  password,
  role,
  fachrichtung,
  arztnummer
) {
  const hash = await bcrypt.hash(password, 10);

  return new Promise((resolve, reject) => {
    db.query(
      `INSERT INTO users
       (first_name, last_name, username, password, role, fachrichtung, arztnummer, active)
       VALUES (?, ?, ?, ?, ?, ?, ?, 1)`,
      [
        first_name,
        last_name,
        username,
        hash,
        role,
        fachrichtung,
        arztnummer
      ],
      err => {
        if (err) {
          if (err.code === "ER_DUP_ENTRY") {
            return reject("Benutzername existiert bereits");
          }
          return reject("Datenbankfehler");
        }
        resolve();
      }
    );
  });
}

function getAllUsers(db) {
  return new Promise((resolve, reject) => {
    db.query(
      `SELECT
         id,
         first_name,
         last_name,
         username,
         role,
         active,
         lock_until
       FROM users
       ORDER BY last_name, first_name`,
      (err, users) => {
        if (err) return reject(err);
        resolve(users);
      }
    );
  });
}

module.exports = {
  createUser,
  getAllUsers
};
