const bcrypt = require("bcrypt");

async function createUser(
  db,
  title,
  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
       (title, first_name, last_name, username, password, role, fachrichtung, arztnummer, active)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)`,
      [
        title,
        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;
}

async function updateUserById(db, userId, data) {
  const { title, first_name, last_name, username, role } = data;

  const [result] = await db.promise().query(
    `
    UPDATE users
    SET title = ?,
        first_name = ?,
        last_name = ?,
        username = ?,
        role = ?
    WHERE id = ?
    `,
    [title, first_name, last_name, username, role, userId]
  );

  return result;
}

module.exports = {
  createUser,
  getAllUsers,
  updateUserById,
};
