import { startPkceFlow } from "../auth/pkce-flow.js";
import { log } from "../lib/log.js";
/**
 * Run the PKCE register flow end-to-end:
 *   1. Bind a loopback callback server, build the auth URL, return URL to operator.
 *   2. Wait for the callback (5-min timeout).
 *   3. Exchange code → tokens; persist encrypted to per-account store.
 *   4. Fetch /me to record graphUserId for log lines.
 *
 * The MCP tool layer prints the auth URL prominently in the tool response so
 * the operator can paste it into the VNC browser.
 */
export async function runAccountRegister(args) {
    const flow = await startPkceFlow({
        clientId: args.clientId,
        tenantId: args.tenantId,
        accountId: args.accountId,
    });
    process.stderr.write(`[outlook-mcp] OPERATOR ACTION: open this URL in the VNC browser to authorize Outlook for account=${args.accountId}:\n${flow.authUrl}\n`);
    const { tokenResponse, scopes } = await flow.result;
    // Fetch /me with the raw access token directly — bypasses TokenStore so we
    // can persist a single, complete blob (with graphUserId) in one write. If
    // /me fails, no tokens hit disk and the operator simply re-runs register.
    const meResp = await fetch("https://graph.microsoft.com/v1.0/me?$select=id,mail,userPrincipalName", {
        headers: { Authorization: `Bearer ${tokenResponse.access_token}` },
    });
    if (!meResp.ok) {
        const text = await meResp.text();
        throw new Error(`Failed to fetch /me after token exchange (status=${meResp.status}): ${text}`);
    }
    const me = (await meResp.json());
    const graphUserId = me.id ?? me.mail ?? me.userPrincipalName ?? "unknown";
    args.tokenStore.store(tokenResponse.access_token, tokenResponse.refresh_token ?? null, tokenResponse.expires_in, { graphUserId, scopes });
    const tokenExpSec = Math.floor((args.tokenStore.read()?.accessTokenExpiry ?? 0) / 1000);
    log({
        event: "auth-ok",
        account: args.accountId,
        graphUserId,
        scopes: scopes.join(","),
        tokenExpSec,
    });
    return {
        status: "registered",
        authUrl: flow.authUrl,
        graphUserId,
        scopes,
        tokenExpSec,
    };
}
//# sourceMappingURL=account-register.js.map