const fs = require("fs");
const os = require("os");
const path = require("path");

const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "lumi-ui-test-"));
process.env.LUMI_DATA_DIR = dataDir;
process.env.NODE_ENV = "test";

const database = require("../../src/services/db");
const { ensureDefaults } = require("../../src/services/settings");
const { createWebServer } = require("../../src/web/server");

database.migrate();
ensureDefaults();

const app = createWebServer({
  discordClient: null,
  commandRouter: null,
  loadPlugins() {}
});
const port = Number(process.env.LUMI_UI_TEST_PORT || process.env.PORT || 3317);
const server = app.listen(port, "127.0.0.1", () => {
  console.log(`Lumi UI fixture listening on http://127.0.0.1:${port}`);
});

function stop() {
  server.close(() => {
    try { database.db.close(); } catch {}
    fs.rmSync(dataDir, { recursive: true, force: true });
    process.exit(0);
  });
}

process.on("SIGINT", stop);
process.on("SIGTERM", stop);
