const http = require("node:http");
const { host, port, defaultUser } = require("./config.cjs");
const { dbPath, ensureDb } = require("./db.cjs");
const { handleAppApi } = require("./app-api.cjs");
const { handleAdminApi } = require("./admin-api.cjs");
const { handleAdminStatic } = require("./static-admin.cjs");
const { sendJson } = require("./http-utils.cjs");
const { nowIso } = require("./security.cjs");
const { readBody } = require("./http-utils.cjs");

function createLocalAuthServer() {
    ensureDb();

    return http.createServer(async (req, res) => {
        const requestUrl = new URL(req.url, `http://${req.headers.host || `${host}:${port}`}`);
        const pathname = requestUrl.pathname.replace(/\/+$/, "") || "/";

        try {
            if (req.method === "OPTIONS") {
                sendJson(res, 200, { success: true });
                return;
            }

            if (req.method === "GET" && (pathname === "/" || pathname === "/health" || pathname === "/api/health")) {
                sendJson(res, 200, { success: true, service: "local-auth", admin: "/admin/", time: nowIso() });
                return;
            }

            if (handleAdminStatic(req, res, requestUrl.pathname)) return;

            const body = ["POST", "PUT", "PATCH"].includes(req.method) ? await readBody(req) : {};
            if (await handleAdminApi(req, res, pathname, body, requestUrl)) return;
            if (await handleAppApi(req, res, pathname, body, requestUrl)) return;

            sendJson(res, 404, { success: false, message: `Local auth endpoint not found: ${req.method} ${pathname}` });
        } catch (error) {
            sendJson(res, 500, { success: false, message: error.message || "Local auth server error" });
        }
    });
}

function start() {
    const server = createLocalAuthServer();
    server.listen(port, host, () => {
        console.log(`[local-auth] running at http://${host}:${port}`);
        console.log(`[local-auth] admin panel: http://${host}:${port}/admin/`);
        console.log(`[local-auth] default account: ${defaultUser.email} / ${defaultUser.password}`);
        console.log(`[local-auth] data file: ${dbPath}`);
    });
    return server;
}

if (require.main === module || module.parent?.filename?.endsWith("local-auth-server.cjs")) {
    start();
}

module.exports = {
    createLocalAuthServer,
    start,
};
