const mysql = require("mysql2");
const { loadConfig } = require("./config-manager");

let pool = null;

function initPool() {
  const config = loadConfig();

  // ✅ Setup-Modus: noch keine config.enc → kein Pool
  if (!config || !config.db) return null;

  return mysql.createPool({
    host: config.db.host,
    port: config.db.port || 3306,
    user: config.db.user,
    password: config.db.password,
    database: config.db.name,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0,
  });
}

function getPool() {
  if (!pool) pool = initPool();
  return pool;
}

function resetPool() {
  pool = null;
}

/**
 * ✅ Proxy damit alter Code weitergeht:
 * const db = require("../db");
 * await db.query(...)
 */
const dbProxy = new Proxy(
  {},
  {
    get(target, prop) {
      const p = getPool();

      if (!p) {
        throw new Error(
          "❌ DB ist noch nicht konfiguriert (config.enc fehlt). Bitte zuerst Setup ausführen: http://127.0.0.1:51777/setup",
        );
      }

      const value = p[prop];

      if (typeof value === "function") {
        return value.bind(p);
      }

      return value;
    },
  },
);

module.exports = dbProxy;
module.exports.getPool = getPool;
module.exports.resetPool = resetPool;
