"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 AppReleases extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(AppReleases);
        const spinner = (0, ora_1.default)(`Fetching releases 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);
            if (flags.current) {
                const release = await service.getCurrentRelease(app.id);
                spinner.stop();
                if (flags.output === 'json') {
                    console.log(JSON.stringify(release, null, 2));
                    return;
                }
                if (!release) {
                    console.log(chalk_1.default.yellow(`\n  No releases for ${app.name}.\n`));
                    return;
                }
                printRelease(app.name, release, true);
                return;
            }
            const releases = (await service.listReleases(app.id)).slice(0, flags.limit);
            spinner.stop();
            if (flags.output === 'json') {
                console.log(JSON.stringify(releases, null, 2));
                return;
            }
            if (releases.length === 0) {
                console.log(chalk_1.default.yellow(`\n  No releases for ${app.name}.\n`));
                return;
            }
            console.log(chalk_1.default.cyan(`\n  Releases — ${app.name}\n`));
            console.log(chalk_1.default.dim(`  ${'STATUS'.padEnd(12)} ${'IMAGE'.padEnd(48)} ${'STARTED'.padEnd(20)} REASON`));
            console.log(chalk_1.default.dim('  ' + '─'.repeat(110)));
            for (const r of releases) {
                const status = colorStatus(r.status).padEnd(21);
                const image = (r.imageRef ?? '').padEnd(48);
                const started = new Date(r.startedAt).toLocaleString().padEnd(20);
                const reason = r.failureReason
                    ? chalk_1.default.red(r.failureReason.slice(0, 60))
                    : '';
                console.log(`  ${status} ${image} ${started} ${reason}`);
            }
            console.log('');
        }
        catch (error) {
            spinner.fail('Failed to fetch releases');
            console.log(chalk_1.default.red(`\n  Error: ${error.message}\n`));
            this.exit(1);
        }
    }
}
AppReleases.description = 'List recent releases (deploy/rollback operations) for an application';
AppReleases.examples = [
    '<%= config.bin %> <%= command.id %> my-api',
    '<%= config.bin %> <%= command.id %> my-api --current',
    '<%= config.bin %> <%= command.id %> my-api --output json',
];
AppReleases.args = {
    name: core_1.Args.string({
        description: 'Application name or slug',
        required: true,
    }),
};
AppReleases.flags = {
    cluster: core_1.Flags.string({ char: 'c' }),
    output: core_1.Flags.string({
        char: 'o',
        options: ['table', 'json'],
        default: 'table',
    }),
    current: core_1.Flags.boolean({
        description: 'Only show the current (most recent) release',
    }),
    limit: core_1.Flags.integer({ char: 'n', default: 10 }),
};
exports.default = AppReleases;
function printRelease(appName, r, current) {
    const title = current
        ? `Current release — ${appName}`
        : `Release — ${appName}`;
    console.log(chalk_1.default.cyan(`\n  ${title}\n`));
    console.log(`  ${chalk_1.default.bold('Status:')}        ${colorStatus(r.status)}`);
    console.log(`  ${chalk_1.default.bold('Operation:')}     ${r.operationId}`);
    if (r.imageRef)
        console.log(`  ${chalk_1.default.bold('Image:')}         ${r.imageRef}`);
    if (r.previousImageRef)
        console.log(`  ${chalk_1.default.bold('Previous:')}      ${chalk_1.default.dim(r.previousImageRef)}`);
    if (r.buildId)
        console.log(`  ${chalk_1.default.bold('Build:')}         ${r.buildId}`);
    console.log(`  ${chalk_1.default.bold('Started:')}       ${new Date(r.startedAt).toLocaleString()}`);
    if (r.completedAt)
        console.log(`  ${chalk_1.default.bold('Completed:')}     ${new Date(r.completedAt).toLocaleString()}`);
    if (r.failureReason)
        console.log(`  ${chalk_1.default.bold('Reason:')}        ${chalk_1.default.red(r.failureReason)}`);
    console.log('');
}
function colorStatus(s) {
    if (s === 'SUCCEEDED')
        return chalk_1.default.green(s);
    if (s === 'FAILED')
        return chalk_1.default.red(s);
    if (s === 'ROLLED_BACK')
        return chalk_1.default.yellow(s);
    return chalk_1.default.blue(s);
}
