import { existsSync, mkdirSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { decodeJwt } from "jose";
import { ZUPLO_AUTH_FILE_NAME } from "../common/constants.js";
import { logger } from "../common/logger.js";
import { printDiagnosticsToConsole } from "../common/output.js";
import { ZUPLO_XDG_STATE_HOME } from "../common/xdg/lib.js";
import { AUTH0_DOMAIN, CLIENT_ID } from "./login.js";
export async function refreshAccessToken(refreshToken) {
    const response = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: new URLSearchParams({
            grant_type: "refresh_token",
            client_id: CLIENT_ID,
            refresh_token: refreshToken,
        }),
    });
    if (!response.ok) {
        throw new Error(`Failed to refresh token: ${response.statusText}`);
    }
    return response.json();
}
export async function getAuthToken() {
    if (!existsSync(join(ZUPLO_XDG_STATE_HOME, ZUPLO_AUTH_FILE_NAME))) {
        return;
    }
    const rawAuth = await readFile(join(ZUPLO_XDG_STATE_HOME, ZUPLO_AUTH_FILE_NAME), "utf-8");
    const authJson = JSON.parse(rawAuth);
    const jwt = decodeJwt(authJson.access_token);
    if (!jwt.exp || jwt.exp < Date.now() / 1000) {
        logger.debug("Access token expired, attempting to get a new one");
        if (authJson.refresh_token) {
            try {
                const newAuth = await refreshAccessToken(authJson.refresh_token);
                await saveAuthState(newAuth);
                return newAuth.access_token;
            }
            catch (error) {
                logger.error(error, `Failed to refresh access token`);
                return;
            }
        }
        return;
    }
    return authJson.access_token;
}
export async function saveAuthState(result) {
    try {
        if (!existsSync(ZUPLO_XDG_STATE_HOME)) {
            mkdirSync(ZUPLO_XDG_STATE_HOME, { recursive: true });
        }
        const tokenPath = join(ZUPLO_XDG_STATE_HOME, ZUPLO_AUTH_FILE_NAME);
        await writeFile(tokenPath, JSON.stringify(result));
    }
    catch (error) {
        logger.error(error, "Failed to save auth state");
        printDiagnosticsToConsole("Failed to save authorization state.");
    }
}
//# sourceMappingURL=tokens.js.map