import { definePlugin, createPluginMethod } from "../../../utils/plugin-utils";
import { LeaseTriggerInboxMessagesSchema, LeaseTriggerInboxMessagesItemSchema, } from "./schemas";
import { ZapierConflictError } from "../../../types/errors";
import { triggerInboxResolver } from "../../../resolvers";
import { resolveTriggerInboxId } from "../utils";
import { triggersDefaults } from "../shared";
// The trigger-inbox API returns 409 from /messages/lease when the inbox
// is paused and fully drained, with the shape:
//   { detail: "...", inbox_attributes: { status, paused_reason, paused_at } }
// (note: top-level `detail`, NOT the standard `{ errors: [...] }`). The
// SDK's generic error parser doesn't recognize this shape, so without a
// customErrorHandler the user gets a vague "HTTP 409" with no reason.
function parseLeaseConflict(data) {
    if (typeof data !== "object" || data === null)
        return {};
    const detail = data.detail;
    const inboxAttributes = data
        .inbox_attributes;
    let pausedReason;
    if (typeof inboxAttributes === "object" && inboxAttributes !== null) {
        const pr = inboxAttributes.paused_reason;
        if (typeof pr === "string" && pr.length > 0)
            pausedReason = pr;
    }
    return {
        detail: typeof detail === "string" ? detail : undefined,
        pausedReason,
    };
}
export const leaseTriggerInboxMessagesPlugin = definePlugin((sdk) => createPluginMethod(sdk, {
    ...triggersDefaults,
    name: "leaseTriggerInboxMessages",
    type: "create",
    itemType: "TriggerInboxLease",
    inputSchema: LeaseTriggerInboxMessagesSchema,
    outputSchema: LeaseTriggerInboxMessagesItemSchema,
    resolvers: {
        inbox: triggerInboxResolver,
        leaseLimit: { type: "static", inputType: "text" },
        leaseSeconds: { type: "static", inputType: "text" },
    },
    handler: async ({ sdk, options }) => {
        const { inbox, leaseLimit, leaseSeconds, signal } = options;
        const inboxId = await resolveTriggerInboxId({
            api: sdk.context.api,
            inbox,
        });
        const requestBody = {};
        if (leaseLimit !== undefined) {
            requestBody.lease_limit = leaseLimit;
        }
        if (leaseSeconds !== undefined) {
            requestBody.lease_seconds = leaseSeconds;
        }
        const rawResponse = await sdk.context.api.post(`/trigger-inbox/api/v1/inboxes/${encodeURIComponent(inboxId)}/messages/lease`, requestBody, {
            authRequired: true,
            signal,
            customErrorHandler: ({ status, data }) => {
                if (status !== 409)
                    return undefined;
                const { detail, pausedReason } = parseLeaseConflict(data);
                const baseMessage = detail ?? "Inbox is paused and fully drained";
                const message = pausedReason
                    ? `${baseMessage} (paused_reason: ${pausedReason})`
                    : baseMessage;
                return new ZapierConflictError(message, {
                    statusCode: status,
                    resourceType: "trigger_inbox",
                });
            },
        });
        return { data: LeaseTriggerInboxMessagesItemSchema.parse(rawResponse) };
    },
}));
