"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 cli_app_service_1 = require("../../lib/services/cli-app.service");
const resolve_cluster_1 = require("../../lib/resolve-cluster");
class AppVersions extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(AppVersions);
        const spinner = (0, ora_1.default)(`Fetching versions for "${args.name}"...`).start();
        try {
            const { id: clusterId } = await (0, resolve_cluster_1.resolveCluster)(flags.cluster);
            const service = await cli_app_service_1.CliAppService.create(clusterId);
            const app = await service.getAppByName(args.name);
            const data = await service.listAvailableVersions(app.id);
            spinner.stop();
            if (flags.output === 'json') {
                console.log(JSON.stringify(data, null, 2));
                return;
            }
            console.log(chalk_1.default.cyan(`\n  Versions — ${app.name}\n`));
            console.log(`  ${chalk_1.default.bold('Source:')}  ${data.sourceType}`);
            console.log(`  ${chalk_1.default.bold('Current:')} ${data.currentImageRef ?? chalk_1.default.dim('—')}`);
            console.log('');
            const versions = data.versions.slice(0, flags.limit);
            if (versions.length === 0) {
                console.log(chalk_1.default.yellow('  No versions found.\n'));
                return;
            }
            console.log(chalk_1.default.dim(`  ${'TAG'.padEnd(20)} ${'DIGEST'.padEnd(15)} ${'CREATED'.padEnd(20)} ${'RELEASES'.padEnd(10)} STATE`));
            console.log(chalk_1.default.dim('  ' + '─'.repeat(100)));
            for (const v of versions) {
                const tag = (v.tag ?? '').padEnd(20);
                const digest = (v.digest ? v.digest.replace('sha256:', '').slice(0, 12) : '').padEnd(15);
                const created = (v.createdAt ? new Date(v.createdAt).toLocaleString() : '-').padEnd(20);
                const rc = String(v.releaseCount).padEnd(10);
                const flags = [];
                if (v.isCurrentlyDeployed)
                    flags.push(chalk_1.default.green('deployed'));
                if (v.isLatestRelease && !v.isCurrentlyDeployed)
                    flags.push(chalk_1.default.yellow('latest-release'));
                if (v.lastRelease?.status === 'FAILED')
                    flags.push(chalk_1.default.red('last-failed'));
                const state = flags.join(' ');
                console.log(`  ${tag} ${digest} ${created} ${rc} ${state}`);
            }
            console.log('');
        }
        catch (error) {
            spinner.fail('Failed to fetch versions');
            console.log(chalk_1.default.red(`\n  Error: ${error.message}\n`));
            this.exit(1);
        }
    }
}
AppVersions.description = 'List image versions available in the registry for an application, with deployment & release status';
AppVersions.examples = [
    '<%= config.bin %> <%= command.id %> my-api',
    '<%= config.bin %> <%= command.id %> my-api --output json',
];
AppVersions.args = {
    name: core_1.Args.string({
        description: 'Application name or slug',
        required: true,
    }),
};
AppVersions.flags = {
    cluster: core_1.Flags.string({ char: 'c' }),
    output: core_1.Flags.string({
        char: 'o',
        options: ['table', 'json'],
        default: 'table',
    }),
    limit: core_1.Flags.integer({ char: 'n', default: 20 }),
};
exports.default = AppVersions;
