import { definePlugin, createPluginMethod } from "../../../utils/plugin-utils";
import { CreateTriggerInboxSchema, TriggerInboxItemSchema } from "./schemas";
import { ZapierConfigurationError } from "../../../types/errors";
import { appKeyResolver, actionKeyResolver, connectionIdResolver, inputsResolver, } from "../../../resolvers";
import { resolveConnectionId } from "../../../utils/domain-utils";
import { triggersDefaults } from "../shared";
export const createTriggerInboxPlugin = definePlugin((sdk) => createPluginMethod(sdk, {
    ...triggersDefaults,
    name: "createTriggerInbox",
    type: "create",
    itemType: "TriggerInbox",
    inputSchema: CreateTriggerInboxSchema,
    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
    // (where it would leak into the SDK method signature and CLI flags).
    resolvers: {
        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 = {}, 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 = {
            subscription: {
                app_key: selectedApi,
                action_key: actionKey,
                inputs,
            },
        };
        if (notificationUrl !== undefined) {
            requestBody.notification_url = notificationUrl;
        }
        if (resolvedConnectionId !== undefined &&
            resolvedConnectionId !== null) {
            requestBody.subscription.connection_id = resolvedConnectionId;
        }
        const rawResponse = await api.post("/trigger-inbox/api/v1/inboxes", requestBody, { authRequired: true });
        return { data: TriggerInboxItemSchema.parse(rawResponse) };
    },
}));
export { CreateTriggerInboxSchema };
