import select from '@inquirer/select';
import { Command, Flags } from '@oclif/core';
import ora from 'ora';
import { loadConfig } from '../../deploy/domain/config.js';
import { initializeSheetsApi, testConnection } from '../../sheets/domain/auth.js';
import { listModulesInSheet } from '../../sheets/sync/sheet-to-yaml.js';
export default class Validate extends Command {
    static description = 'Validate connection and format of a Google Sheet.';
    static examples = [
        '<%= config.bin %> sheets validate --bc iam',
    ];
    static flags = {
        bc: Flags.string({
            description: 'Bounded context name',
        }),
        config: Flags.string({
            char: 'c',
            default: './aurora.yaml',
            description: 'Path to aurora.yaml config file',
        }),
    };
    async run() {
        const { flags } = await this.parse(Validate);
        const config = loadConfig(flags.config);
        if (!config.sheets) {
            this.error('No "sheets" section found in aurora.yaml.\n' +
                'Add a sheets.bounded_contexts block to your config.');
        }
        const allNames = Object.keys(config.sheets.boundedContexts);
        if (allNames.length === 0) {
            this.error('No bounded contexts configured in sheets section.');
        }
        let bcName;
        if (flags.bc) {
            if (!config.sheets.boundedContexts[flags.bc]) {
                this.error(`Bounded context "${flags.bc}" not found.\nAvailable: ${allNames.join(', ')}`);
            }
            bcName = flags.bc;
        }
        else {
            bcName = await select({
                choices: allNames.map((name) => ({
                    description: config.sheets.boundedContexts[name].description,
                    name,
                    value: name,
                })),
                message: 'Select a bounded context to validate:',
            });
        }
        const bcConfig = config.sheets.boundedContexts[bcName];
        const spinner = ora('Authenticating with Google Sheets...').start();
        const sheetsApi = await initializeSheetsApi();
        spinner.succeed('Authenticated with Google Sheets');
        spinner.start('Testing connection...');
        await testConnection(sheetsApi, bcConfig.spreadsheetId);
        spinner.succeed('Connection successful');
        spinner.start('Reading modules...');
        const modules = await listModulesInSheet(sheetsApi, bcConfig.spreadsheetId);
        spinner.succeed(`Found ${modules.length} modules`);
        this.log('\nModules in spreadsheet:');
        for (const mod of modules) {
            this.log(`  ${mod}`);
        }
    }
}
