"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 AppBuilds extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(AppBuilds);
        const spinner = (0, ora_1.default)(`Fetching builds 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 builds = (await service.listBuilds(app.id)).slice(0, flags.limit);
            spinner.stop();
            if (flags.output === 'json') {
                console.log(JSON.stringify(builds, null, 2));
                return;
            }
            if (builds.length === 0) {
                console.log(chalk_1.default.yellow(`\n  No builds found for ${app.name}.\n`));
                return;
            }
            console.log(chalk_1.default.cyan(`\n  Builds for ${app.name}\n`));
            console.log(chalk_1.default.dim(`  ${'STATUS'.padEnd(11)} ${'PROVIDER'.padEnd(16)} ${'BRANCH'.padEnd(14)} ${'COMMIT'.padEnd(10)} ${'STARTED'.padEnd(20)} URL`));
            console.log(chalk_1.default.dim('  ' + '─'.repeat(100)));
            for (const b of builds) {
                const status = colorBuildStatus(b.status ?? 'PENDING').padEnd(20);
                const provider = (b.provider ?? '-').padEnd(16);
                const branch = (b.branch ?? '-').padEnd(14);
                const commit = ((b.commitSha ?? '').slice(0, 7) || '-').padEnd(10);
                const started = b.startedAt
                    ? new Date(b.startedAt).toLocaleString().padEnd(20)
                    : chalk_1.default.dim('-'.padEnd(20));
                const url = b.externalUrl ?? '';
                console.log(`  ${status} ${provider} ${branch} ${commit} ${started} ${chalk_1.default.dim(url)}`);
            }
            console.log('');
        }
        catch (error) {
            spinner.fail('Failed to fetch builds');
            console.log(chalk_1.default.red(`\n  Error: ${error.message}\n`));
            this.exit(1);
        }
    }
}
AppBuilds.description = 'List recent builds for an application';
AppBuilds.examples = [
    '<%= config.bin %> <%= command.id %> my-api',
    '<%= config.bin %> <%= command.id %> my-api --output json',
    '<%= config.bin %> <%= command.id %> my-api --limit 5',
];
AppBuilds.args = {
    name: core_1.Args.string({
        description: 'Application name or slug',
        required: true,
    }),
};
AppBuilds.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: 10 }),
};
exports.default = AppBuilds;
function colorBuildStatus(s) {
    if (s === 'COMPLETED')
        return chalk_1.default.green(s);
    if (s === 'FAILED' || s === 'CANCELLED')
        return chalk_1.default.red(s);
    if (s === 'PENDING')
        return chalk_1.default.dim(s);
    return chalk_1.default.blue(s);
}
