import { toIterable } from "../utils/pagination-utils";
async function fetchConnections(sdk, resolvedParams) {
    const context = sdk.context;
    const includeShared = await context.hasCapability?.("canIncludeSharedConnections");
    return toIterable(sdk.listConnections({
        app: resolvedParams.app,
        includeShared: includeShared || undefined,
    }));
}
function promptForConnection(connections, params) {
    return {
        type: "list",
        name: "connection",
        message: params.app
            ? `Select connection for ${params.app}:`
            : "Select connection:",
        choices: connections.map((connection) => ({
            name: connection.title || connection.label || "Connection",
            value: connection.id,
        })),
    };
}
export const connectionIdResolver = {
    type: "dynamic",
    depends: ["app"],
    requireCapabilities: ["canIncludeSharedConnections"],
    tryResolveWithoutPrompt: async (sdk, params) => {
        if (!params.app)
            return null;
        try {
            const app = await sdk.getApp({ app: params.app });
            if (!app.data.auth_type) {
                return { resolvedValue: undefined };
            }
        }
        catch {
            // If we can't determine auth type, fall through to normal connection prompt
        }
        return null;
    },
    fetch: fetchConnections,
    prompt: promptForConnection,
};
// Generic version without app dependency. tryResolveWithoutPrompt is intentionally
// absent: without app we cannot look up auth_type to determine if auth is required.
export const connectionIdGenericResolver = {
    type: "dynamic",
    depends: [],
    requireCapabilities: ["canIncludeSharedConnections"],
    fetch: fetchConnections,
    prompt: promptForConnection,
};
