import { ProviderProfileAuthService, ProviderProfileAuthServiceError, } from "./ProviderProfileAuthService.js";
import { providerProfileCredentialRef } from "./providerProfiles.js";
export class OpenAiApiKeyValidationError extends Error {
    constructor(message) {
        super(message);
        this.name = "OpenAiApiKeyValidationError";
    }
}
export class OpenAiProviderAuthService {
    #providerProfiles;
    constructor(vault, broker) {
        this.#providerProfiles = new ProviderProfileAuthService(vault, broker);
    }
    async statusOpenAiApiKey(workspaceId) {
        return formatOpenAiApiKeyStatus(workspaceId, await this.#providerProfiles.statusApiKeyInternal(workspaceId, "openai"));
    }
    validateOpenAiApiKey(apiKey) {
        try {
            this.#providerProfiles.validateApiKey(apiKey);
        }
        catch (error) {
            throw translateOpenAiApiKeyValidationError(error);
        }
    }
    async putOpenAiApiKey(workspaceId, apiKey) {
        try {
            return formatOpenAiApiKeyStatus(workspaceId, await this.#providerProfiles.putApiKeyInternal(workspaceId, "openai", apiKey));
        }
        catch (error) {
            throw translateOpenAiApiKeyValidationError(error);
        }
    }
    async revokeOpenAiApiKey(workspaceId) {
        return formatOpenAiApiKeyStatus(workspaceId, await this.#providerProfiles.revokeApiKeyInternal(workspaceId, "openai"));
    }
}
export function refForWorkspace(workspaceId) {
    return providerProfileCredentialRef(workspaceId, "openai");
}
function translateOpenAiApiKeyValidationError(error) {
    if (error instanceof ProviderProfileAuthServiceError &&
        error.code === "invalid_credential") {
        throw new OpenAiApiKeyValidationError(toOpenAiApiKeyMessage(error.message));
    }
    throw error;
}
function toOpenAiApiKeyMessage(message) {
    if (message === "API key is required.")
        return "apiKey is required.";
    if (message === "API key exceeds the 4096 character limit.") {
        return "apiKey exceeds the 4096 character limit.";
    }
    return "apiKey is invalid.";
}
function formatOpenAiApiKeyStatus(workspaceId, status) {
    return {
        provider: "openai",
        kind: "openai_api_key",
        workspaceId,
        state: status.state,
        ...(status.maskedLabel ? { maskedLabel: status.maskedLabel } : {}),
        ...(status.updatedAt ? { updatedAt: status.updatedAt } : {}),
        ...(status.credentialVersion
            ? { credentialVersion: status.credentialVersion }
            : {}),
        ...(status.backend ? { backend: status.backend } : {}),
        ...(status.degraded !== undefined ? { degraded: status.degraded } : {}),
    };
}
