import { CliError } from '../../errors/index.js';
import { checkbox, confirm, input, select } from '@inquirer/prompts';
function isAbortError(error) {
    return (error instanceof Error &&
        (error.name === 'ExitPromptError' ||
            error.message.includes('User force closed')));
}
export async function confirmAction(message, ctx) {
    if (!ctx.interactive) {
        return false;
    }
    try {
        return await confirm({ message, default: false });
    }
    catch (error) {
        if (isAbortError(error)) {
            return false;
        }
        throw error;
    }
}
export async function inputRequired(message, ctx) {
    if (!ctx.interactive) {
        throw new CliError('Input prompt requires interactive mode.', 1);
    }
    try {
        const value = (await input({ message })).trim();
        if (value.length === 0) {
            throw new CliError('Input is required.', 1);
        }
        return value;
    }
    catch (error) {
        if (isAbortError(error)) {
            return null;
        }
        throw error;
    }
}
export async function inputWithDefault(message, defaultValue, ctx) {
    if (!ctx.interactive) {
        throw new CliError('Input prompt requires interactive mode.', 1);
    }
    try {
        const value = (await input({
            message,
            default: defaultValue,
        })).trim();
        return value.length === 0 ? defaultValue : value;
    }
    catch (error) {
        if (isAbortError(error)) {
            return null;
        }
        throw error;
    }
}
export async function selectWithAbort(message, choices, ctx) {
    if (!ctx.interactive) {
        throw new CliError('Selection prompt requires interactive mode.', 1);
    }
    try {
        const selected = await select({
            message,
            choices: choices.map((choice) => ({
                name: choice.label,
                value: choice.value,
                description: choice.description,
            })),
        });
        return selected;
    }
    catch (error) {
        if (isAbortError(error)) {
            return null;
        }
        throw error;
    }
}
export async function selectManyWithAbort(message, choices, ctx) {
    if (!ctx.interactive) {
        throw new CliError('Selection prompt requires interactive mode.', 1);
    }
    try {
        const selected = await checkbox({
            message,
            choices: choices.map((choice) => ({
                name: choice.label,
                value: choice.value,
                description: choice.description,
                checked: choice.checked,
            })),
            required: false,
        });
        return selected;
    }
    catch (error) {
        if (isAbortError(error)) {
            return null;
        }
        throw error;
    }
}
export async function selectManyOrEmpty(message, choices, ctx) {
    const selected = await selectManyWithAbort(message, choices, ctx);
    return selected ?? [];
}
