import http from "node:http";
import { fileURLToPath } from "node:url";
import { handleRoomsRequest } from "./router.js";
const MAX_BODY_BYTES = 256 * 1024;
export function startRoomsDevServer(port, deps) {
    const server = http.createServer(async (req, res) => {
        let body = undefined;
        try {
            const raw = await readBody(req);
            body = raw.length > 0 ? JSON.parse(raw) : undefined;
        }
        catch {
            res.writeHead(400, { "content-type": "application/json" });
            res.end(JSON.stringify({ error: { code: "invalid_json", message: "Body must be JSON" } }));
            return;
        }
        const url = new URL(req.url ?? "/", "http://localhost");
        const result = await handleRoomsRequest({
            method: req.method ?? "GET",
            path: url.pathname,
            header: (name) => {
                const value = req.headers[name.toLowerCase()];
                return Array.isArray(value) ? (value[0] ?? null) : (value ?? null);
            },
            body,
        }, deps);
        res.writeHead(result.status, { "content-type": result.contentType });
        res.end(result.body);
    });
    return new Promise((resolve) => {
        server.listen(port, "127.0.0.1", () => resolve(server));
    });
}
function readBody(req) {
    return new Promise((resolve, reject) => {
        const chunks = [];
        let size = 0;
        req.on("data", (chunk) => {
            size += chunk.length;
            if (size > MAX_BODY_BYTES) {
                reject(new Error("body too large"));
                req.destroy();
                return;
            }
            chunks.push(chunk);
        });
        req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
        req.on("error", reject);
    });
}
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
    const port = Number(process.env.ROOMS_DEV_PORT ?? 8789);
    const { createAccessTokenVerifier } = await import("@zaparo/k-identity/verify");
    const base = process.env.K_BASE_URL ?? "https://k.kbsoap.com";
    const tenant = process.env.K_TENANT ?? "zaparo";
    const verifyAccessToken = createAccessTokenVerifier(`${base}/t/${tenant}`);
    const allowed = new Set((process.env.K_APP_IDS ?? "").split(",").map((id) => id.trim()).filter(Boolean));
    const envKnownApps = () => async (appId) => allowed.has(appId);
    startRoomsDevServer(port, { verifyToken: verifyAccessToken, knownApps: envKnownApps() }).then(() => {
        console.log(`[rooms] dev server on http://127.0.0.1:${port}`);
    });
}
