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();
      }
    );
  });
}

async function getAllUsers(db, search = null) {
  let sql = `
    SELECT *
    FROM users
    WHERE 1=1
  `;
  const params = [];

  if (search) {
    sql += `
      AND (
        first_name LIKE ?
        OR last_name LIKE ?
        OR username LIKE ?
      )
    `;
    const q = `%${search}%`;
    params.push(q, q, q);
  }

  sql += " ORDER BY last_name, first_name";

  const [rows] = await db.promise().query(sql, params);
  return rows;
}

module.exports = {
  createUser,
  getAllUsers,
};
