"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@oclif/core");
const chalk_1 = __importDefault(require("chalk"));
const ora_1 = __importDefault(require("ora"));
const api_client_1 = require("../../lib/api-client");
const config_storage_1 = require("../../lib/config-storage");
const prompts_1 = require("../../lib/prompts");
class IntegrationRemoveInstallation extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(IntegrationRemoveInstallation);
        const installationId = Number(args.installationId);
        if (!Number.isInteger(installationId) || installationId <= 0) {
            this.error(`Invalid installation ID "${args.installationId}". Must be a positive integer.`, { exit: 1 });
        }
        const configStorage = new config_storage_1.ConfigStorage();
        const apiUrl = configStorage.getApiUrlOrThrow();
        const apiKey = configStorage.getApiKey();
        if (!apiKey) {
            this.error('Not logged in. Run `flui auth login` first.', { exit: 1 });
        }
        const api = new api_client_1.ApiClient({ baseUrl: apiUrl, apiKey });
        if (!flags.yes) {
            const ok = await (0, prompts_1.confirmPrompt)(`Remove GitHub App installation ${chalk_1.default.bold(installationId)} from Flui's database?`, false);
            if (!ok) {
                console.log(chalk_1.default.dim('\n  Cancelled.\n'));
                return;
            }
        }
        const spinner = (0, ora_1.default)(`Removing installation ${installationId}…`).start();
        try {
            await api.delete(`/repositories/github-app/installations/${installationId}`);
            spinner.succeed(`Removed installation ${installationId}`);
        }
        catch (error) {
            spinner.fail('Failed to remove installation');
            if (error instanceof api_client_1.ApiError && error.statusCode === 403) {
                console.log(chalk_1.default.yellow('  Admin privileges required for this operation.'));
            }
            else if (error instanceof api_client_1.ApiError && error.statusCode === 404) {
                console.log(chalk_1.default.yellow(`  No installation with ID ${installationId} found. Run \`flui integration installations\` to list tracked ones.`));
            }
            else {
                console.log(chalk_1.default.red(`  ${error.message}`));
            }
            this.exit(1);
        }
    }
}
IntegrationRemoveInstallation.description = 'Remove a GitHub App installation record from the Flui database. Requires admin privileges. Does NOT uninstall the app on GitHub — uninstall it there first, otherwise the next webhook will re-create the record.';
IntegrationRemoveInstallation.examples = [
    '<%= config.bin %> <%= command.id %> 12345678',
    '<%= config.bin %> <%= command.id %> 12345678 --yes',
];
IntegrationRemoveInstallation.args = {
    installationId: core_1.Args.string({
        description: 'GitHub installation ID (numeric). Get it with `flui integration installations`.',
        required: true,
    }),
};
IntegrationRemoveInstallation.flags = {
    yes: core_1.Flags.boolean({
        char: 'y',
        description: 'Skip the confirmation prompt',
        default: false,
    }),
};
exports.default = IntegrationRemoveInstallation;
