import { ZapierAppNotFoundError, ZapierNotFoundError } from "../types/errors";
import { getAppKeyList } from "../utils/domain-utils";
export const appKeyResolver = {
    type: "dynamic",
    inputType: "search",
    placeholder: "e.g., 'slack' or 'SlackCLIAPI' or 'mail'",
    // Try the user's typed string as an exact app locator first; getApp accepts
    // a slug, key, or implementation id. If that hits, short-circuit with the
    // input — every variant the user could have typed is already a valid value
    // anywhere else app is required, so no canonicalization needed here. If
    // getApp 404s, fall back to a search; any other error (auth, network,
    // rate-limit) propagates so the user sees the real problem.
    fetch: async (sdk, { search }) => {
        if (!search)
            return [];
        try {
            await sdk.getApp({ app: search });
            return search;
        }
        catch (err) {
            // ZapierAppNotFoundError and ZapierNotFoundError are independent
            // siblings under ZapierError, not parent/child — so neither
            // instanceof check subsumes the other. getApp throws the
            // app-specific class today; the generic one stays here for 404s
            // that arrive through other layers (e.g. an intermediate plugin
            // wrapping the error, or a future endpoint refactor that drops
            // the app-specific class). Any other class (auth, network, rate
            // limit) propagates so the user sees the real problem.
            if (!(err instanceof ZapierAppNotFoundError) &&
                !(err instanceof ZapierNotFoundError)) {
                throw err;
            }
        }
        const page = await sdk.listApps({ search });
        return page.data;
    },
    prompt: (apps) => ({
        type: "list",
        name: "app",
        message: "Select app:",
        choices: apps.map((app) => ({
            name: app.title || app.key,
            hint: app.title ? getAppKeyList(app) : undefined,
            value: app.key,
        })),
    }),
};
