import { CONTROL_PLANE_HOST, CONTROL_PLANE_PORT } from "@pocketcoder/shared";
import { clearTokens } from "../../auth/token-storage.js";
import { deleteMachineKey, getMachineKey } from "../../utils/machine-key.js";
import { isDaemonRunning } from "./start.js";
/**
 * Stop the daemon if it's running.
 * Returns true if the daemon was stopped, false if it wasn't running.
 */
async function stopDaemonIfRunning() {
    const running = await isDaemonRunning();
    if (!running)
        return false;
    try {
        const url = `http://${CONTROL_PLANE_HOST}:${CONTROL_PLANE_PORT}/stop`;
        const response = await fetch(url, {
            method: "POST",
            signal: AbortSignal.timeout(5000),
        });
        return response.ok;
    }
    catch {
        return false;
    }
}
/**
 * Handle the `pocketcoder logout` CLI command.
 * Stops Host daemon, clears auth tokens, and regenerates machine key.
 * Preserves projects database and logs.
 */
export async function logoutCommand() {
    try {
        // 1. Stop daemon if running
        const wasStopped = await stopDaemonIfRunning();
        if (wasStopped) {
            console.log("Daemon stopped");
        }
        // 2. Clear auth tokens (deletes auth.json)
        await clearTokens();
        // 3. Regenerate machine key (delete old, generate new)
        await deleteMachineKey();
        await getMachineKey();
        console.log("Logged out");
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        console.error(`Logout failed: ${message}`);
        process.exitCode = 1;
    }
}
//# sourceMappingURL=logout.js.map