"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.startLocalServer = startLocalServer;
const http_1 = __importDefault(require("http"));
/**
 * Start a local server for OAuth callbacks
 */
function startLocalServer(callback) {
    return new Promise((resolve, reject) => {
        const server = http_1.default.createServer(async (req, res) => {
            try {
                let body = "";
                req.on("data", chunk => {
                    body += chunk.toString();
                });
                req.on("end", () => {
                    const params = new URLSearchParams(body);
                    const paramObj = {};
                    params.forEach((value, key) => {
                        paramObj[key] = value;
                    });
                    callback(paramObj);
                    res.writeHead(200, { "Content-Type": "text/html" });
                    res.end("<h1>Authentication successful! You can close this window.</h1>");
                });
            }
            catch (error) {
                console.error("Error in callback server:", error);
                res.writeHead(500, { "Content-Type": "text/plain" });
                res.end("Internal server error");
            }
        });
        server.on("error", (err) => {
            reject(err);
        });
        server.listen(0, "localhost", () => {
            const address = server.address();
            const port = address.port;
            resolve({
                port,
                close: () => {
                    server.close();
                }
            });
        });
    });
}
//# sourceMappingURL=server.js.map