import { ZapierResourceNotFoundError } from "../../types/errors";
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/**
 * Resolves an `inbox` locator (UUID or name) to a UUID.
 *
 * Per the locator rule, the value is loose: the API takes a UUID, but the
 * SDK accepts either form. UUID-shaped inputs pass through unchanged;
 * anything else is looked up by name via `GET /inboxes?name=...`.
 *
 * Edge case: if a user names an inbox with a UUID-shaped string, this
 * method treats it as a UUID. To target a UUID-shaped name, use
 * `listTriggerInboxes({ name })` to get the actual UUID, then pass that.
 */
export async function resolveTriggerInboxId({ api, inbox, }) {
    if (UUID_REGEX.test(inbox)) {
        return inbox;
    }
    const rawResponse = await api.get("/trigger-inbox/api/v1/inboxes", {
        searchParams: { name: inbox, limit: "1" },
        authRequired: true,
    });
    const response = rawResponse;
    const id = response.results?.[0]?.id;
    if (!id) {
        throw new ZapierResourceNotFoundError(`No trigger inbox named "${inbox}" found.`, { resourceType: "trigger_inbox", resourceId: inbox });
    }
    return id;
}
/**
 * Pulls `errors[0].detail` off a JSON:API-style error response body.
 * Returns `undefined` for any shape that doesn't match, so callers can
 * fall back to a default message.
 */
export function extractErrorDetail(data) {
    if (typeof data !== "object" || data === null)
        return undefined;
    const errors = data.errors;
    if (!Array.isArray(errors) || errors.length === 0)
        return undefined;
    const first = errors[0];
    if (typeof first !== "object" || first === null)
        return undefined;
    const detail = first.detail;
    return typeof detail === "string" ? detail : undefined;
}
