const db = require("../db");
const {  createUser,  getAllUsers} = require("../services/admin.service");
const bcrypt = require("bcrypt");

async function listUsers(req, res) {
  try {
    const users = await getAllUsers(db);
    res.render("admin_users", {
      users,
      currentUser: req.session.user
    });
  } catch (err) {
    console.error(err);
    res.send("Datenbankfehler");
  }
}

function showCreateUser(req, res) {
  res.render("admin_create_user", {
    error: null,
    user: req.session.user
  });
}

async function postCreateUser(req, res) {
  let {
    first_name,
    last_name,
    username,
    password,
    role,
    fachrichtung,
    arztnummer
  } = req.body;

  first_name  = first_name?.trim();
  last_name   = last_name?.trim();
  username    = username?.trim();
  fachrichtung = fachrichtung?.trim();
  arztnummer   = arztnummer?.trim();

  // 🔴 Grundvalidierung
  if (!first_name || !last_name || !username || !password || !role) {
    return res.render("admin_create_user", {
      error: "Alle Pflichtfelder müssen ausgefüllt sein",
      user: req.session.user
    });
  }

  // 🔴 Arzt-spezifische Validierung
  if (role === "arzt") {
    if (!fachrichtung || !arztnummer) {
      return res.render("admin_create_user", {
        error: "Für Ärzte sind Fachrichtung und Arztnummer Pflicht",
        user: req.session.user
      });
    }
  } else {
    // Sicherheit: Mitarbeiter dürfen keine Arzt-Daten haben
    fachrichtung = null;
    arztnummer = null;
  }

  try {
    await createUser(
      db,
      first_name,
      last_name,
      username,
      password,
      role,
      fachrichtung,
      arztnummer
    );

    req.session.flash = {
      type: "success",
      message: "Benutzer erfolgreich angelegt"
    };

    res.redirect("/admin/users");

  } catch (error) {
    res.render("admin_create_user", {
      error,
      user: req.session.user
    });
  }
}


async function changeUserRole(req, res) {
  const userId = req.params.id;
  const { role } = req.body;

  if (!["arzt", "mitarbeiter"].includes(role)) {
    req.session.flash = { type: "danger", message: "Ungültige Rolle" };
    return res.redirect("/admin/users");
  }

  db.query(
    "UPDATE users SET role = ? WHERE id = ?",
    [role, userId],
    err => {
      if (err) {
        console.error(err);
        req.session.flash = { type: "danger", message: "Fehler beim Ändern der Rolle" };
      } else {
        req.session.flash = { type: "success", message: "Rolle erfolgreich geändert" };
      }
      res.redirect("/admin/users");
    }
  );
}

async function resetUserPassword(req, res) {
  const userId = req.params.id;
  const { password } = req.body;

  if (!password || password.length < 4) {
    req.session.flash = { type: "warning", message: "Passwort zu kurz" };
    return res.redirect("/admin/users");
  }

  const hash = await bcrypt.hash(password, 10);
  
  db.query(
    "UPDATE users SET password = ? WHERE id = ?",
    [hash, userId],
    err => {
      if (err) {
        console.error(err);
        req.session.flash = { type: "danger", message: "Fehler beim Zurücksetzen" };
      } else {
        req.session.flash = { type: "success", message: "Passwort zurückgesetzt" };
      }
      res.redirect("/admin/users");
    }
  );
}


module.exports = {
  listUsers,
  showCreateUser,
  postCreateUser,
  changeUserRole,
  resetUserPassword
};
