import { Command, Flags } from '@oclif/core';
import ora from 'ora';
import { loadConfig } from '../../deploy/domain/config.js';
import { resolveEnvironments } from '../../deploy/domain/plan-builder.js';
import { triggerDeploy } from '../../deploy/domain/trigger.js';
export default class Deploy extends Command {
    static description = 'Trigger deploy by pushing source branches to environments/{env}.';
    static examples = [
        '<%= config.bin %> deploy',
        '<%= config.bin %> deploy --env dev',
        '<%= config.bin %> deploy --dry-run',
        '<%= config.bin %> deploy --env prod -c ../aurora.yaml',
    ];
    static flags = {
        config: Flags.string({
            char: 'c',
            default: './aurora.yaml',
            description: 'Path to aurora.yaml config file',
        }),
        'dry-run': Flags.boolean({
            default: false,
            description: 'Show what would be pushed without executing',
        }),
        env: Flags.string({
            description: 'Deploy only this environment (e.g. dev, qa, prod)',
        }),
    };
    async run() {
        const { flags } = await this.parse(Deploy);
        const config = loadConfig(flags.config);
        const environments = resolveEnvironments(config, flags.env);
        let hasErrors = false;
        for (const env of environments) {
            const envConfig = config.environments.get(env);
            const { source } = envConfig;
            const spinner = ora(`Deploying ${env} (${source} → environments/${env})`).start();
            try {
                const result = triggerDeploy({
                    dryRun: flags['dry-run'],
                    environment: env,
                    source,
                });
                if (result.status === 'skipped') {
                    spinner.info(`[dry-run] ${result.message}`);
                }
                else {
                    spinner.succeed(`Pushed ${source} → ${result.ref}`);
                }
            }
            catch (error) {
                hasErrors = true;
                spinner.fail(error instanceof Error ? error.message : String(error));
            }
        }
        if (hasErrors) {
            this.error('Some environments failed to deploy.');
        }
    }
}
