import { createLogger } from '../logger.js';
import { AuthError } from '../errors.js';
const logger = createLogger('oauth-utils');
export const DEFAULT_AUTH_PROFILE = 'default';
export async function discoverTokenEndpoint(serverUrl) {
    const discoveryUrls = [
        `${serverUrl}/.well-known/oauth-authorization-server`,
        `${serverUrl}/.well-known/openid-configuration`,
    ];
    for (const url of discoveryUrls) {
        try {
            logger.debug(`Trying OAuth discovery at: ${url}`);
            const response = await fetch(url, {
                headers: { Accept: 'application/json' },
            });
            if (response.ok) {
                const metadata = await response.json();
                if (metadata.token_endpoint) {
                    logger.debug(`Found token endpoint: ${metadata.token_endpoint}`);
                    return metadata.token_endpoint;
                }
            }
        }
        catch {
        }
    }
    return undefined;
}
export async function refreshAccessToken(tokenEndpoint, refreshToken, clientId) {
    logger.debug(`Refreshing token at: ${tokenEndpoint}`);
    const params = new URLSearchParams({
        grant_type: 'refresh_token',
        refresh_token: refreshToken,
        client_id: clientId,
    });
    const response = await fetch(tokenEndpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Accept: 'application/json',
        },
        body: params.toString(),
    });
    if (!response.ok) {
        const errorText = await response.text();
        logger.error(`Token refresh failed: ${response.status} ${errorText}`);
        if (response.status === 400 || response.status === 401) {
            throw new AuthError('Refresh token is invalid or expired');
        }
        throw new AuthError(`Failed to refresh token: ${response.status} ${response.statusText}`);
    }
    const tokenResponse = await response.json();
    return tokenResponse;
}
export async function discoverAndRefreshToken(serverUrl, refreshToken, clientId) {
    const tokenEndpoint = await discoverTokenEndpoint(serverUrl);
    if (!tokenEndpoint) {
        throw new AuthError(`Could not find OAuth token endpoint for ${serverUrl}`);
    }
    return refreshAccessToken(tokenEndpoint, refreshToken, clientId);
}
export function createReauthError(serverUrl, profileName, message) {
    const command = profileName === DEFAULT_AUTH_PROFILE
        ? `mcpc ${serverUrl} login`
        : `mcpc ${serverUrl} login --profile ${profileName}`;
    return new AuthError(`${message}. Please re-authenticate with: ${command}`);
}
//# sourceMappingURL=oauth-utils.js.map