import { logger } from "../../utils/logger.js";
import { sendDaemonRegister } from "../../gateway/messages/daemon-register.js";
let providers = null;
export function setReRegisterProviders(p) {
    providers = p;
}
const RESPONSE_TIMEOUT_MS = 10_000;
export async function reRegisterRoutes(app) {
    app.post("/re-register", async (_request, reply) => {
        if (!providers) {
            return reply.status(503).send({ error: "Daemon not fully initialized" });
        }
        const client = providers.getGatewayClient();
        if (!client || !client.connected) {
            return reply.status(200).send({ sent: false, reason: "not_connected" });
        }
        try {
            const label = providers.getLabel();
            // Set up a one-shot listener for daemon_register_response
            const responsePromise = new Promise((resolve) => {
                const timer = setTimeout(() => {
                    client.off("message", listener);
                    resolve(null);
                }, RESPONSE_TIMEOUT_MS);
                const listener = (msg) => {
                    if (msg.type === "daemon_register_response") {
                        clearTimeout(timer);
                        client.off("message", listener);
                        resolve(msg.payload);
                    }
                };
                client.on("message", listener);
            });
            const sent = await sendDaemonRegister(client, label);
            if (!sent) {
                return reply.status(200).send({ sent: false, reason: "not_authenticated" });
            }
            logger.info("Re-sent daemon_register to gateway (triggered by project change)");
            // Wait for response
            const responsePayload = await responsePromise;
            if (responsePayload?.warning === "PROJECT_LIMIT_EXCEEDED") {
                logger.warn(`Project limit exceeded: ${responsePayload.message ?? `${responsePayload.ignored} project(s) ignored`}`);
            }
            return reply.status(200).send({
                sent: true,
                response: responsePayload ?? undefined,
            });
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            logger.error(`Failed to re-register: ${message}`);
            return reply.status(500).send({ error: message });
        }
    });
}
//# sourceMappingURL=re-register.js.map