// server.js
// Express app bootstrap for Nginx vhost generator/updater


// server.js
import express from "express";
import morgan from "morgan";
import nginxRouter from "./routes/nginx.js";
import dotenv from "dotenv";

dotenv.config(); // loads .env if present

// ---- Static defaults (env first, fallback second) ----
export const STATIC_IP = process.env.STATIC_IP || "147.93.40.215";
export const PARENT_PATH = process.env.PARENT_PATH || "/home/user/conf/web"; // <parent>/<domain>/
export const PUBLIC_WEB_ROOT = process.env.PUBLIC_WEB_ROOT || "/home/user/web"; // for /error alias
export const ERROR_LOG_ROOT = process.env.ERROR_LOG_ROOT || "/var/log/apache2/domains";

// How to restart Nginx (can be "reload" or full "restart")
export const NGINX_RELOAD_CMD = process.env.NGINX_RELOAD_CMD || "systemctl reload nginx";

// -----------------------------------------------------

const app = express();
app.use(express.json({ limit: "256kb" }));
app.use(morgan("tiny"));

// health
app.get("/healthz", (_req, res) => res.json({ ok: true }));

// api
app.use("/api", nginxRouter);

// 404
app.use((_req, res) => res.status(404).json({ ok: false, error: "Not found" }));

const PORT = process.env.PORT || 5055;
app.listen(PORT, () => {
    console.log(`Nginx generator API listening on port ${PORT}`);
    console.log(`Defaults -> IP: ${STATIC_IP}, PARENT_PATH: ${PARENT_PATH}`);
});
