"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 AppRedeploy extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(AppRedeploy);
        if (!flags.build && !args.target) {
            this.error('Provide either a tag/digest argument or --build <buildId>.');
        }
        const spinner = (0, ora_1.default)(`Triggering redeploy 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.build) {
                await service.deployFromBuild(app.id, flags.build);
                spinner.succeed(`Redeploy triggered for ${app.name} from build ${flags.build}`);
                return;
            }
            await service.redeployTag(app.id, args.target);
            spinner.succeed(`Redeploy triggered for ${app.name} with image "${args.target}"`);
            console.log(chalk_1.default.dim(`\n  Run "flui app release ${args.name} --watch" to follow rollout.\n`));
        }
        catch (error) {
            spinner.fail('Redeploy failed');
            console.log(chalk_1.default.red(`\n  Error: ${error.message}\n`));
            this.exit(1);
        }
    }
}
AppRedeploy.description = 'Redeploy an application from an existing image (tag or digest), without rebuilding';
AppRedeploy.examples = [
    '<%= config.bin %> <%= command.id %> my-api a1cac27',
    '<%= config.bin %> <%= command.id %> my-api sha256:812bdfd0a833...',
    '<%= config.bin %> <%= command.id %> my-api --build <buildId>',
];
AppRedeploy.args = {
    name: core_1.Args.string({
        description: 'Application name or slug',
        required: true,
    }),
    target: core_1.Args.string({
        description: 'Tag, short digest (12+ hex), or full sha256:<digest>',
        required: false,
    }),
};
AppRedeploy.flags = {
    cluster: core_1.Flags.string({ char: 'c' }),
    build: core_1.Flags.string({
        description: 'Deploy from an existing build id (alternative to tag/digest)',
    }),
};
exports.default = AppRedeploy;
