const { configExists, loadConfig } = require("../config-manager");

/**
 * Leitet beim ersten Programmstart automatisch zu /setup um,
 * solange config.enc fehlt oder DB-Daten unvollständig sind.
 */
module.exports = function requireSetup(req, res, next) {
  // ✅ Setup immer erlauben
  if (req.path.startsWith("/setup")) return next();

  // ✅ Static niemals blockieren
  if (req.path.startsWith("/public")) return next();
  if (req.path.startsWith("/css")) return next();
  if (req.path.startsWith("/js")) return next();
  if (req.path.startsWith("/images")) return next();
  if (req.path.startsWith("/uploads")) return next();
  if (req.path.startsWith("/favicon")) return next();

  // ✅ Login/Logout erlauben
  if (req.path.startsWith("/login")) return next();
  if (req.path.startsWith("/logout")) return next();

  // ✅ Wenn config.enc fehlt -> Setup erzwingen
  if (!configExists()) {
    return res.redirect("/setup");
  }

  // ✅ Wenn config existiert aber DB Daten fehlen -> Setup erzwingen
  let cfg = null;
  try {
    cfg = loadConfig();
  } catch (e) {
    cfg = null;
  }

  const ok =
    cfg?.db?.host &&
    cfg?.db?.user &&
    cfg?.db?.password &&
    cfg?.db?.name;

  if (!ok) {
    return res.redirect("/setup");
  }

  next();
};
