const express = require("express");
const router = express.Router();
const mysql = require("mysql2/promise");

// ✅ nutzt deinen bestehenden config-manager (NICHT utils/config!)
const { configExists, saveConfig } = require("../config-manager");

// ✅ DB + Session Reset (wie in deiner app.js)
const db = require("../db");
const { resetSessionStore } = require("../config/session");

/**
 * Setup darf nur laufen, wenn config.enc NICHT existiert
 * (sonst könnte jeder die DB später überschreiben)
 */
function blockIfInstalled(req, res, next) {
  if (configExists()) {
    return res.redirect("/");
  }
  next();
}

/**
 * Setup Form anzeigen
 */
router.get("/", blockIfInstalled, (req, res) => {
  return res.render("setup/index", {
    title: "Erstinstallation",
    defaults: {
      host: "127.0.0.1",
      port: 3306,
      user: "",
      password: "",
      name: "",
    },
  });
});

/**
 * ✅ Verbindung testen (AJAX)
 */
router.post("/test", blockIfInstalled, async (req, res) => {
  try {
    const { host, port, user, password, name } = req.body;

    if (!host || !user || !name) {
      return res.status(400).json({
        ok: false,
        message: "Bitte Host, Benutzer und Datenbankname ausfüllen.",
      });
    }

    const connection = await mysql.createConnection({
      host,
      port: Number(port || 3306),
      user,
      password,
      database: name,
      connectTimeout: 5000,
    });

    await connection.query("SELECT 1");
    await connection.end();

    return res.json({ ok: true, message: "✅ Verbindung erfolgreich!" });
  } catch (err) {
    return res.status(500).json({
      ok: false,
      message: "❌ Verbindung fehlgeschlagen: " + err.message,
    });
  }
});

/**
 * ✅ Setup speichern (DB Daten in config.enc)
 */
router.post("/", blockIfInstalled, async (req, res) => {
  try {
    const { host, port, user, password, name } = req.body;

    if (!host || !user || !name) {
      req.session.flash = req.session.flash || [];
      req.session.flash.push({
        type: "danger",
        message: "❌ Bitte Host, Benutzer und Datenbankname ausfüllen.",
      });
      return res.redirect("/setup");
    }

    // ✅ Verbindung testen bevor speichern
    const connection = await mysql.createConnection({
      host,
      port: Number(port || 3306),
      user,
      password,
      database: name,
      connectTimeout: 5000,
    });

    await connection.query("SELECT 1");
    await connection.end();

    // ✅ speichern
    saveConfig({
      db: {
        host,
        port: Number(port || 3306),
        user,
        password,
        name,
      },
    });

    // ✅ DB Pool neu starten (damit neue config sofort aktiv ist)
    if (typeof db.resetPool === "function") {
      db.resetPool();
    }

    // ✅ Session Store neu starten
    resetSessionStore();

    req.session.flash = req.session.flash || [];
    req.session.flash.push({
      type: "success",
      message: "✅ Setup abgeschlossen. Du kannst dich jetzt einloggen.",
    });

    return res.redirect("/login");
  } catch (err) {
    req.session.flash = req.session.flash || [];
    req.session.flash.push({
      type: "danger",
      message: "❌ Setup fehlgeschlagen: " + err.message,
    });
    return res.redirect("/setup");
  }
});

module.exports = router;
