import { definePlugin } from "../../utils/plugin-utils";
import { createPaginatedPluginMethod } from "../../utils/plugin-utils";
import { normalizeActionItem } from "../../utils/domain-utils";
import { ListActionsInputSchema } from "./schemas";
import { ActionItemSchema } from "../../schemas/Action";
import { ZapierConfigurationError } from "../../types/errors";
import { DEFAULT_PAGE_SIZE } from "../../constants";
import { appKeyResolver, actionTypeResolver } from "../../resolvers";
import { setMethodMetadata } from "../../utils/telemetry-context";
export const listActionsPlugin = definePlugin((sdk) => createPaginatedPluginMethod(sdk, {
    name: "listActions",
    categories: ["action"],
    type: "list",
    itemType: "Action",
    inputSchema: ListActionsInputSchema,
    outputSchema: ActionItemSchema,
    defaultPageSize: DEFAULT_PAGE_SIZE,
    resolvers: { app: appKeyResolver, actionType: actionTypeResolver },
    handler: async ({ sdk, options, }) => {
        const { api, getVersionedImplementationId } = sdk.context;
        const appKey = "app" in options ? options.app : options.appKey;
        const selectedApi = await getVersionedImplementationId(appKey);
        if (!selectedApi) {
            throw new ZapierConfigurationError("No current_implementation_id found for app", { configType: "current_implementation_id" });
        }
        // operationKey intentionally omitted — listActions is a list-level
        // operation with no specific action key.
        setMethodMetadata({
            selectedApi,
            operationType: options.actionType ?? null,
        });
        const data = await api.get("/zapier/api/v4/implementations/", {
            searchParams: {
                global: "true",
                public_only: "true",
                selected_apis: selectedApi,
            },
        });
        let allActions = [];
        for (const implementation of data.results || []) {
            if (implementation.actions) {
                for (const action of implementation.actions) {
                    allActions.push(normalizeActionItem({
                        ...action,
                        selected_api: action.selected_api || implementation.selected_api,
                    }));
                }
            }
        }
        if (options.actionType) {
            allActions = allActions.filter((action) => action.action_type === options.actionType);
        }
        return { data: allActions };
    },
}));
