const path = require("node:path");
const { adminPanelDir } = require("./config.cjs");
const { redirect, serveFile, safeJoin } = require("./http-utils.cjs");

function handleAdminStatic(req, res, pathname) {
    if (req.method !== "GET") return false;

    if (pathname === "/admin") {
        redirect(res, "/admin/");
        return true;
    }

    if (pathname === "/admin/") {
        serveFile(res, path.join(adminPanelDir, "index.html"));
        return true;
    }

    if (pathname.startsWith("/admin/")) {
        const filePath = safeJoin(adminPanelDir, pathname.replace(/^\/admin\//, ""));
        if (!filePath) return false;
        const ext = path.extname(filePath).toLowerCase();
        const contentType = {
            ".css": "text/css; charset=utf-8",
            ".js": "text/javascript; charset=utf-8",
            ".json": "application/json; charset=utf-8",
            ".png": "image/png",
            ".jpg": "image/jpeg",
            ".jpeg": "image/jpeg",
            ".svg": "image/svg+xml",
        }[ext] || "application/octet-stream";
        serveFile(res, filePath, contentType);
        return true;
    }

    return false;
}

module.exports = {
    handleAdminStatic,
};
