import { UserInputError } from "./errors-D_R568zP.js";
import { ApiClientError, ApiNotFoundError } from "./errors-CQZ-QlOB.js";
import { SentryApiService } from "./client-CWgvrDHH.js";
import { validateRegionUrl } from "./validate-region-url-CaR6XWB_.js";

//#region src/internal/tool-helpers/api.ts
/**
* Create a Sentry API service from server context with optional region override
* @param context - Server context containing host and access token
* @param opts - Options object containing optional regionUrl override
* @returns Configured SentryApiService instance (always uses HTTPS)
* @throws {UserInputError} When regionUrl is provided but invalid
*/
function apiServiceFromContext(context, opts = {}) {
	let host = context.sentryHost;
	if (opts.regionUrl?.trim()) {
		const baseHost = context.sentryHost || "sentry.io";
		host = validateRegionUrl(opts.regionUrl.trim(), baseHost);
	}
	return new SentryApiService({
		host,
		accessToken: context.accessToken
	});
}
/**
* Maps API errors to user-friendly errors based on context
* @param error - The error to handle
* @param params - The parameters that were used in the API call
* @returns Never - always throws an error
* @throws {UserInputError} For 4xx errors that are likely user input issues
* @throws {Error} For other errors
*/
function handleApiError(error, params) {
	if (error instanceof ApiClientError) {
		let message = `API error (${error.status}): ${error.message}`;
		if (error instanceof ApiNotFoundError && params) {
			const paramsList = [];
			for (const [key, value] of Object.entries(params)) if (value !== void 0 && value !== null && value !== "") paramsList.push(`${key}: '${value}'`);
			if (paramsList.length > 0) message = `Resource not found (404): ${error.message}\nPlease verify these parameters are correct:\n${paramsList.map((p) => `  - ${p}`).join("\n")}`;
		}
		throw new UserInputError(message, { cause: error });
	}
	throw error;
}
/**
* Wraps an async API call with automatic error handling
* @param fn - The async function to execute
* @param params - The parameters that were used in the API call
* @returns The result of the function
* @throws {UserInputError} For user input errors
* @throws {Error} For other errors
*/
async function withApiErrorHandling(fn, params) {
	try {
		return await fn();
	} catch (error) {
		handleApiError(error, params);
	}
}

//#endregion
export { apiServiceFromContext, handleApiError, withApiErrorHandling };
//# sourceMappingURL=api-CkLTFexT.js.map