const bcrypt = require("bcrypt");

async function loginUser(db, username, password, lockTimeMinutes) {
  return new Promise((resolve, reject) => {
    db.query(
      "SELECT * FROM users WHERE username = ?",
      [username],
      async (err, results) => {
        if (err || results.length === 0) {
          return reject("Login fehlgeschlagen");
        }

        const user = results[0];
        const now = new Date();

        if (user.active === 0) {
          return reject("Account deaktiviert");
        }

        if (user.lock_until && new Date(user.lock_until) > now) {
          return reject(`Account gesperrt bis ${user.lock_until}`);
        }

        const match = await bcrypt.compare(password, user.password);

        if (!match) {
          let sql = "failed_attempts = failed_attempts + 1";
          if (user.failed_attempts + 1 >= 3) {
            sql += `, lock_until = DATE_ADD(NOW(), INTERVAL ${lockTimeMinutes} MINUTE)`;
          }
          db.query(`UPDATE users SET ${sql} WHERE id = ?`, [user.id]);
          return reject("Falsches Passwort");
        }

        db.query(
          "UPDATE users SET failed_attempts = 0, lock_until = NULL WHERE id = ?",
          [user.id]
        );

        resolve({
          id: user.id,
          username: user.username,
          role: user.role,
          title: user.title,
          firstname: user.first_name,
          lastname: user.last_name
        });
      }
    );
  });
}

module.exports = { loginUser };
