"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");
const format_bytes_1 = require("../../../lib/format-bytes");
class AppBackupCreate extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(AppBackupCreate);
        let destination;
        if (flags.bucket) {
            if (!flags.endpoint) {
                this.error('--endpoint is required when --bucket is set');
            }
            if (!flags['access-key'] || !flags['secret-key']) {
                this.error('S3 credentials missing. Pass --access-key/--secret-key or set FLUI_S3_ACCESS_KEY/FLUI_S3_SECRET_KEY.');
            }
            destination = {
                bucket: flags.bucket,
                endpoint: flags.endpoint,
                region: flags.region,
                accessKeyId: flags['access-key'],
                secretAccessKey: flags['secret-key'],
                keyPrefix: flags['key-prefix'],
            };
        }
        const target = destination
            ? `s3://${destination.bucket}`
            : 'auto-provisioned bucket';
        const spinner = (0, ora_1.default)(`Backing up "${args.name}" to ${target}...`).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 backup = await service.createAppBackup(app.id, {
                volumeName: flags.volume,
                description: flags.description,
                destination,
            });
            spinner.succeed(`Backup uploaded: ${backup.exportId}`);
            console.log('');
            console.log(`  ${chalk_1.default.bold('Provider:')}  ${backup.provider}`);
            console.log(`  ${chalk_1.default.bold('Namespace:')} ${backup.namespace}`);
            console.log(`  ${chalk_1.default.bold('Source:')}    ${backup.sourcePvcName}`);
            console.log(`  ${chalk_1.default.bold('Source request:')}  ${backup.sizeGb} GiB`);
            const uploaded = backup.actualBytes === undefined
                ? 'unknown'
                : (0, format_bytes_1.formatBytes)(backup.actualBytes);
            console.log(`  ${chalk_1.default.bold('Uploaded:')}        ${uploaded}`);
            console.log(`  ${chalk_1.default.bold('Bucket:')}    ${backup.destination.bucket}`);
            console.log(`  ${chalk_1.default.bold('Endpoint:')}  ${backup.destination.endpoint}`);
            console.log(`  ${chalk_1.default.bold('Prefix:')}    ${backup.exportId}`);
            console.log(`  ${chalk_1.default.bold('Created:')}   ${backup.createdAt}`);
            console.log('');
            if (!destination) {
                console.log(chalk_1.default.dim(`  Bucket auto-provisioned by ${backup.provider} object storage.`));
            }
            console.log('');
        }
        catch (error) {
            spinner.fail('Backup failed');
            const msg = error.response?.data?.message ?? error.message ?? String(error);
            console.log(chalk_1.default.red(`\n  Error: ${msg}\n`));
            this.exit(1);
        }
    }
}
AppBackupCreate.description = 'Archive an application volume to S3-compatible object storage. ' +
    'When --bucket is omitted the cluster provider auto-provisions one ' +
    '(Scaleway: full-auto using your compute key; Hetzner: requires Object ' +
    'Storage credentials connected). Otherwise pass an explicit endpoint + ' +
    '--bucket and S3 credentials via flags or FLUI_S3_ACCESS_KEY/FLUI_S3_SECRET_KEY env.';
AppBackupCreate.examples = [
    '<%= config.bin %> <%= command.id %> my-app',
    '<%= config.bin %> <%= command.id %> my-app --description nightly',
    '<%= config.bin %> <%= command.id %> my-app -b external-bucket -e https://s3.eu-central-1.amazonaws.com -r eu-central-1',
];
AppBackupCreate.args = {
    name: core_1.Args.string({
        description: 'Application name or slug',
        required: true,
    }),
};
AppBackupCreate.flags = {
    cluster: core_1.Flags.string({
        char: 'c',
        description: 'Cluster name or ID (default: auto-detect)',
    }),
    volume: core_1.Flags.string({
        char: 'v',
        description: 'Volume (PVC) name when the app has multiple volumes. Required if more than one PVC exists.',
    }),
    description: core_1.Flags.string({
        char: 'd',
        description: 'Optional human-friendly tag appended to the key prefix',
    }),
    bucket: core_1.Flags.string({
        char: 'b',
        description: 'Destination S3 bucket name. Omit to auto-provision via the cluster provider.',
    }),
    endpoint: core_1.Flags.string({
        char: 'e',
        description: 'S3 endpoint URL (required when --bucket is set). Examples: ' +
            'https://s3.fr-par.scw.cloud, https://s3.eu-central-1.amazonaws.com',
    }),
    region: core_1.Flags.string({
        char: 'r',
        description: 'S3 region',
        default: 'auto',
    }),
    'access-key': core_1.Flags.string({
        description: 'S3 access key. Defaults to FLUI_S3_ACCESS_KEY env var.',
        env: 'FLUI_S3_ACCESS_KEY',
    }),
    'secret-key': core_1.Flags.string({
        description: 'S3 secret key. Defaults to FLUI_S3_SECRET_KEY env var.',
        env: 'FLUI_S3_SECRET_KEY',
    }),
    'key-prefix': core_1.Flags.string({
        description: 'Override the destination key prefix (default: flui/<cluster>/<app>/<timestamp>/)',
    }),
};
exports.default = AppBackupCreate;
