import { definePlugin } from "../../utils/plugin-utils";
import { createPluginMethod } from "../../utils/plugin-utils";
import { GetActionInputFieldsSchemaInputSchema } from "./schemas";
import { ZapierConfigurationError } from "../../types/errors";
import { appKeyResolver, actionTypeResolver, actionKeyResolver, connectionIdResolver, inputsAllOptionalResolver, } from "../../resolvers";
import { fetchImplementationNeeds } from "../../services/implementations";
import { resolveConnectionId } from "../../utils/domain-utils";
import { setMethodMetadata } from "../../utils/telemetry-context";
export const getActionInputFieldsSchemaPlugin = definePlugin((sdk) => createPluginMethod(sdk, {
    name: "getActionInputFieldsSchema",
    categories: ["action"],
    type: "item",
    itemType: "InputSchema",
    inputSchema: GetActionInputFieldsSchemaInputSchema,
    resolvers: {
        app: appKeyResolver,
        actionType: actionTypeResolver,
        action: actionKeyResolver,
        connection: connectionIdResolver,
        inputs: inputsAllOptionalResolver,
    },
    handler: async ({ sdk, options, }) => {
        const { api, getVersionedImplementationId } = sdk.context;
        const appKey = "app" in options ? options.app : options.appKey;
        const actionKey = "action" in options ? options.action : options.actionKey;
        const { actionType, connection, connectionId, authenticationId, inputs, } = options;
        const resolvedConnectionId = await resolveConnectionId({
            connection,
            connectionId,
            authenticationId,
            resolveConnection: sdk.context.resolveConnection,
        });
        const selectedApi = await getVersionedImplementationId(appKey);
        if (!selectedApi) {
            throw new ZapierConfigurationError("No current_implementation_id found for app", { configType: "current_implementation_id" });
        }
        setMethodMetadata({
            selectedApi,
            operationType: actionType,
            operationKey: actionKey,
        });
        const { data: action } = await sdk.getAction({
            app: appKey,
            actionType,
            action: actionKey,
        });
        const needsData = await fetchImplementationNeeds({
            api,
            selectedApi,
            action: action.key,
            actionType,
            connectionId: resolvedConnectionId ?? null,
            inputs,
        });
        return { data: needsData.schema || {} };
    },
}));
