import { definePlugin, createPluginMethod } from "../../../utils/plugin-utils";
import { EnsureTriggerInboxSchema, TriggerInboxItemSchema } from "./schemas";
import { ZapierConfigurationError, ZapierConflictError, } from "../../../types/errors";
import { appKeyResolver, actionKeyResolver, connectionIdResolver, inputsResolver, } from "../../../resolvers";
import { resolveConnectionId } from "../../../utils/domain-utils";
import { triggersDefaults } from "../shared";
import { extractErrorDetail } from "../utils";
export const ensureTriggerInboxPlugin = definePlugin((sdk) => createPluginMethod(sdk, {
    ...triggersDefaults,
    name: "ensureTriggerInbox",
    type: "create",
    itemType: "TriggerInbox",
    inputSchema: EnsureTriggerInboxSchema,
    outputSchema: TriggerInboxItemSchema,
    // actionKeyResolver and inputsResolver depend on actionType, which is
    // always "read" for triggers. Pin it as a constant resolver so it's
    // seeded into resolvedParams without polluting the user-facing schema.
    resolvers: {
        name: { type: "static", inputType: "text" },
        app: appKeyResolver,
        action: actionKeyResolver,
        connection: connectionIdResolver,
        inputs: inputsResolver,
        actionType: { type: "constant", value: "read" },
    },
    handler: async ({ sdk, options }) => {
        const { api } = sdk.context;
        const { app: appKey, action: actionKey, connection, inputs = {}, name, notificationUrl, } = options;
        const resolvedConnectionId = await resolveConnectionId({
            connection,
            resolveConnection: sdk.context.resolveConnection,
        });
        const selectedApi = await sdk.context.getVersionedImplementationId(appKey);
        if (!selectedApi) {
            throw new ZapierConfigurationError(`No current_implementation_id found for app "${appKey}"`, { configType: "current_implementation_id" });
        }
        const requestBody = {
            name,
            subscription: {
                app_key: selectedApi,
                action_key: actionKey,
                inputs,
                connection_id: resolvedConnectionId ?? null,
            },
        };
        if (notificationUrl !== undefined) {
            requestBody.notification_url = notificationUrl;
        }
        const rawResponse = await api.post("/trigger-inbox/api/v1/inboxes", requestBody, {
            authRequired: true,
            customErrorHandler: ({ status, data }) => {
                if (status === 409) {
                    const detail = extractErrorDetail(data);
                    return new ZapierConflictError(detail ??
                        `An inbox named "${name}" already exists with a different subscription.`, { statusCode: status, resourceType: "trigger_inbox" });
                }
                return undefined;
            },
        });
        return { data: TriggerInboxItemSchema.parse(rawResponse) };
    },
}));
export { EnsureTriggerInboxSchema };
