import fs from "node:fs/promises";
import { getAppPaths } from "@prestyj/core";
import { log } from "../logger.js";
/**
 * File-backed store for remote-MCP OAuth credentials, living next to the CLI's
 * other auth at `~/.ezcoder/mcp-auth.json`. Keyed by server name (the same identity
 * the config + UI use). Every read re-reads the file so concurrent sidecars /
 * windows see each other's logins; writes are read-modify-write so two servers
 * don't clobber one another.
 */
export class McpOAuthStore {
    filePath;
    constructor(filePath = getAppPaths().mcpAuthFile) {
        this.filePath = filePath;
    }
    async readAll() {
        try {
            const raw = await fs.readFile(this.filePath, "utf-8");
            const parsed = JSON.parse(raw);
            return { version: 1, servers: parsed.servers ?? {} };
        }
        catch {
            return { version: 1, servers: {} };
        }
    }
    async writeAll(data) {
        try {
            await fs.writeFile(this.filePath, JSON.stringify(data, null, 2), {
                encoding: "utf-8",
                mode: 0o600,
            });
        }
        catch (err) {
            log("WARN", "mcp", "failed to persist MCP OAuth store", {
                message: err instanceof Error ? err.message : String(err),
            });
        }
    }
    async get(name) {
        const all = await this.readAll();
        return all.servers[name] ?? {};
    }
    /** Merge a partial entry into the server's record (read-modify-write). */
    async patch(name, patch) {
        const all = await this.readAll();
        all.servers[name] = { ...(all.servers[name] ?? {}), ...patch };
        await this.writeAll(all);
    }
    /** Drop a server's whole OAuth record (used on logout / removal). */
    async clear(name) {
        const all = await this.readAll();
        if (all.servers[name]) {
            delete all.servers[name];
            await this.writeAll(all);
        }
    }
    /** Whether this server has saved tokens (i.e. has completed login at least once). */
    async hasTokens(name) {
        const entry = await this.get(name);
        return !!entry.tokens?.access_token;
    }
}
//# sourceMappingURL=oauth-store.js.map