import http from "node:http";
import opn from "open";
import { printCriticalFailureToConsoleAndExit } from "../common/output.js";
import { html } from "./html.js";
import { AUTH_SERVER_PORT } from "./login.js";
export async function browserAuth(authorizationUrl) {
    let params;
    const handler = (req, res) => {
        if (!req.url) {
            throw new Error("Bad url");
        }
        const url = new URL(req.url, `http://localhost:${AUTH_SERVER_PORT}`);
        if (url.pathname === "/") {
            params = url.searchParams;
            res.writeHead(200, { "Content-Type": "text/html" });
            res.end(html);
        }
        else {
            res.end("Unsupported route for login server.");
        }
    };
    const server = http.createServer(handler).listen(AUTH_SERVER_PORT);
    await opn(authorizationUrl);
    let iterations = 0;
    while (params === undefined) {
        if (iterations++ > 600) {
            server.close();
            await printCriticalFailureToConsoleAndExit("Timed out waiting for login in the browser. Run the zuplo login command again.");
        }
        else {
            await new Promise((resolve) => setTimeout(resolve, 500));
        }
    }
    server.close();
    return params;
}
//# sourceMappingURL=server.js.map