import fs from "node:fs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { getE2EOAuthSetupsDir } from "./artifacts.js";
const SETUP_TTL_MS = 10 * 60 * 1000;
export function createOAuthSetupSession(input) {
    const now = Date.now();
    const session = {
        setupId: `e2e_setup_${randomUUID().replace(/-/g, "").slice(0, 12)}`,
        expectedEmail: input.expectedEmail,
        scopes: input.scopes,
        redirectUri: input.redirectUri,
        state: randomUUID(),
        createdAt: new Date(now).toISOString(),
        expiresAt: new Date(now + SETUP_TTL_MS).toISOString(),
        requestSource: input.requestSource,
        channel: input.channel,
        sender: input.sender,
    };
    saveOAuthSetupSession(session);
    return session;
}
export function saveOAuthSetupSession(session) {
    const dir = getE2EOAuthSetupsDir();
    fs.mkdirSync(dir, { recursive: true });
    fs.writeFileSync(path.join(dir, `${session.setupId}.json`), `${JSON.stringify(session, null, 2)}\n`, "utf-8");
}
export function loadOAuthSetupSession(setupId) {
    const file = path.join(getE2EOAuthSetupsDir(), `${setupId}.json`);
    if (!fs.existsSync(file))
        return null;
    try {
        const session = JSON.parse(fs.readFileSync(file, "utf-8"));
        if (Date.parse(session.expiresAt) < Date.now()) {
            deleteOAuthSetupSession(setupId);
            return null;
        }
        return session;
    }
    catch {
        return null;
    }
}
export function deleteOAuthSetupSession(setupId) {
    const file = path.join(getE2EOAuthSetupsDir(), `${setupId}.json`);
    if (fs.existsSync(file))
        fs.unlinkSync(file);
}
export function parseCallbackUrl(callbackUrl) {
    const url = new URL(callbackUrl.trim());
    const code = url.searchParams.get("code");
    if (!code)
        throw new Error("Callback URL is missing authorization code");
    return { code, state: url.searchParams.get("state") ?? undefined };
}
//# sourceMappingURL=oauth-setup-store.js.map