"use strict";
/**
 * Helper functions for interacting with Keycloak OAuth2 server
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateKeycloakHealth = exports.getAccessToken = void 0;
const DEFAULT_KEYCLOAK_URL = process.env.KEYCLOAK_URL || 'http://127.0.0.1:18080';
const DEFAULT_REALM = 'camunda-platform';
const DEFAULT_CLIENT_ID = 'zeebe';
const DEFAULT_CLIENT_SECRET = 'zecobe-secret';
/**
 * Fetches an OAuth2 access token from Keycloak using client credentials flow
 * @param realm - Keycloak realm name
 * @param clientId - OAuth2 client ID
 * @param clientSecret - OAuth2 client secret
 * @param keycloakUrl - Base URL of Keycloak server
 * @returns Access token string
 */
async function getAccessToken(realm = DEFAULT_REALM, clientId = DEFAULT_CLIENT_ID, clientSecret = DEFAULT_CLIENT_SECRET, keycloakUrl = DEFAULT_KEYCLOAK_URL) {
    const tokenEndpoint = `${keycloakUrl}/realms/${realm}/protocol/openid-connect/token`;
    const params = new URLSearchParams();
    params.append('grant_type', 'client_credentials');
    params.append('client_id', clientId);
    params.append('client_secret', clientSecret);
    try {
        const response = await fetch(tokenEndpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params.toString(),
        });
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`Failed to fetch access token from Keycloak: ${response.status} ${response.statusText}\n${errorText}`);
        }
        const data = await response.json();
        if (!data.access_token) {
            throw new Error('Access token not found in Keycloak response: ' + JSON.stringify(data));
        }
        return data.access_token;
    }
    catch (error) {
        if (error instanceof Error) {
            throw new Error(`Error fetching Keycloak access token: ${error.message}`);
        }
        throw error;
    }
}
exports.getAccessToken = getAccessToken;
/**
 * Validates that Keycloak server is healthy and accessible
 * @param keycloakUrl - Base URL of Keycloak server
 */
async function validateKeycloakHealth(keycloakUrl = DEFAULT_KEYCLOAK_URL) {
    // Check if the camunda-platform realm is accessible instead of health endpoint
    // since Keycloak 23+ may not expose health endpoints by default
    const realmEndpoint = `${keycloakUrl}/realms/camunda-platform`;
    try {
        const response = await fetch(realmEndpoint, {
            method: 'GET',
        });
        if (!response.ok) {
            throw new Error(`Keycloak realm check failed: ${response.status} ${response.statusText}`);
        }
        console.log(`Keycloak server is healthy at ${keycloakUrl}`);
    }
    catch (error) {
        if (error instanceof Error) {
            throw new Error(`Keycloak server is not available at ${keycloakUrl}: ${error.message}\n` +
                'Make sure Keycloak is running with: docker run -d --name keycloak -p 18080:8080 ' +
                '-e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin ' +
                'quay.io/keycloak/keycloak:23.0 start-dev');
        }
        throw error;
    }
}
exports.validateKeycloakHealth = validateKeycloakHealth;
