import { WorkspaceScopedResource, extractData } from './base.js';
export const EXTERNAL_USER_SESSION_CREATE_SCOPE = 'external_user_sessions:create';
const omitAuthorizationHeader = {
    onRequest({ request }) {
        request.headers.delete('Authorization');
        return request;
    },
};
function setAuthorizationHeader(accessToken) {
    return {
        onRequest({ request }) {
            request.headers.set('Authorization', `Bearer ${accessToken}`);
            return request;
        },
    };
}
function formBody(fields) {
    const body = new URLSearchParams();
    for (const [key, value] of Object.entries(fields)) {
        if (value !== undefined)
            body.set(key, value);
    }
    return body;
}
/**
 * Identity token operations exposed through the platform API base URL.
 *
 * The identity service's token endpoint is mounted at `POST /token` on the
 * same base URL used for the platform API.
 */
export class TokensResource extends WorkspaceScopedResource {
    /** Exchange an API key for an identity-issued JWT access token. */
    async exchangeApiKey(request) {
        const body = formBody({
            grant_type: 'api_key',
            api_key: request.apiKey,
            scope: request.scope,
        });
        return extractData(await this.client.POST('/token', {
            body,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            middleware: [omitAuthorizationHeader],
        }));
    }
    /**
     * Exchange OAuth client credentials for a parent JWT.
     *
     * External integration credentials must request only
     * `external_user_sessions:create`; that parent token is a delegation
     * credential for minting external-user sessions, not a general platform API
     * token.
     */
    async exchangeClientCredentials(request) {
        const body = formBody({
            grant_type: 'client_credentials',
            client_id: request.clientId,
            client_secret: request.clientSecret,
            scope: request.scope,
        });
        return extractData(await this.client.POST('/token', {
            body,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            middleware: [omitAuthorizationHeader],
        }));
    }
    /**
     * Mint a short-lived external-user session token from a parent
     * external-integration JWT.
     */
    async createExternalUserSession(request) {
        const body = formBody({
            grant_type: 'external_user_session',
            workspace_id: request.workspaceId ?? this.workspaceId,
            external_subject_key: request.externalSubjectKey,
            subject_type: request.subjectType,
            service_id: request.serviceId,
            consumer_entity_id: request.consumerEntityId,
            ttl_seconds: request.ttlSeconds === undefined ? undefined : String(request.ttlSeconds),
            scope: request.scope,
        });
        return extractData(await this.client.POST('/token', {
            body,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            ...(request.parentAccessToken && {
                middleware: [setAuthorizationHeader(request.parentAccessToken)],
            }),
        }));
    }
    /** Rotate a refresh token for a new access-token and refresh-token pair. */
    async refresh(request) {
        const body = formBody({
            grant_type: 'refresh_token',
            refresh_token: request.refreshToken,
            workspace_id: request.workspaceId,
            scope: request.scope,
        });
        return extractData(await this.client.POST('/token', {
            body,
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            middleware: [omitAuthorizationHeader],
        }));
    }
}
//# sourceMappingURL=tokens.js.map