/*!
 * Copyright (C) Microsoft Corporation. All rights reserved.
 */
import { ConfidentialClientApplication } from '@azure/msal-node';
import { getAuthority } from '../CliUtils.js';
/**
 * note: This is meant for use in CI only since it hardcodes the authority & tenant ID.
 */
export class ServicePrincipalAuthenticationProvider {
    _msalClient;
    _clientId;
    _clientSecret;
    _tenantId;
    _region;
    constructor() {
        if (!process.env.SP_CLIENT_ID || !process.env.SP_CLIENT_SECRET || !process.env.SP_TENANT_ID) {
            throw new Error('Service Principal environment variables SP_CLIENT_ID, SP_CLIENT_SECRET, and SP_TENANT_ID must be set');
        }
        this._clientId = process.env.SP_CLIENT_ID;
        this._clientSecret = process.env.SP_CLIENT_SECRET;
        this._tenantId = process.env.SP_TENANT_ID;
    }
    async initAsync(region) {
        this._region = region;
        const authConfig = {
            auth: {
                clientId: this._clientId,
                clientSecret: this._clientSecret,
                authority: getAuthority(this._region, this._tenantId),
            },
        };
        this._msalClient = new ConfidentialClientApplication(authConfig);
    }
    async getAccessTokenForResource(resource) {
        if (!this._msalClient) {
            throw new Error('Authentication not initialized yet');
        }
        const clientCredentialRequest = {
            scopes: [resource + '/.default'],
        };
        const result = await this._msalClient.acquireTokenByClientCredential(clientCredentialRequest);
        if (!result?.accessToken) {
            throw new Error('Failed to acquire token using service principal');
        }
        return result.accessToken;
    }
    getUserTenantId() {
        return this._tenantId;
    }
}
//# sourceMappingURL=ServicePrincipalAuthenticationProvider.js.map