"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 api_client_1 = require("../../lib/api-client");
const config_storage_1 = require("../../lib/config-storage");
class RepoList extends core_1.Command {
    async run() {
        const { flags } = await this.parse(RepoList);
        const configStorage = new config_storage_1.ConfigStorage();
        const apiUrl = configStorage.getApiUrlOrThrow();
        const apiKey = configStorage.getApiKey();
        if (!apiKey) {
            this.error('Not logged in. Run `flui auth login` first.', { exit: 1 });
        }
        const api = new api_client_1.ApiClient({ baseUrl: apiUrl, apiKey });
        let repos;
        try {
            repos = await api.get('/repositories');
        }
        catch (error) {
            this.error(`Failed to list repositories: ${error.message}`, {
                exit: 1,
            });
        }
        if (flags.output === 'json') {
            console.log(JSON.stringify(repos, null, 2));
            return;
        }
        if (repos.length === 0) {
            console.log(chalk_1.default.dim('\n  No repositories connected.'));
            console.log(chalk_1.default.dim('  Connect one with `flui repo connect <owner/repo>` ' +
                '(or `flui integration connect github` first if GitHub is not yet connected).\n'));
            return;
        }
        const refW = Math.max(...repos.map((r) => r.repositoryFullName.length), 4);
        const langW = Math.max(...repos.map((r) => (r.language ?? '-').length), 4);
        console.log('');
        console.log(`  ${chalk_1.default.bold('REPOSITORY'.padEnd(refW))}  ${chalk_1.default.bold('BRANCH'.padEnd(8))}  ${chalk_1.default.bold('LANG'.padEnd(langW))}  ${chalk_1.default.bold('AUTO-DEPLOY')}`);
        console.log(`  ${'─'.repeat(refW)}  ${'─'.repeat(8)}  ${'─'.repeat(langW)}  ${'─'.repeat(11)}`);
        for (const r of repos) {
            const autoDeploy = r.autoDeployEnabled
                ? chalk_1.default.green('on')
                : chalk_1.default.dim('off');
            console.log(`  ${r.repositoryFullName.padEnd(refW)}  ${r.defaultBranch.padEnd(8)}  ${(r.language ?? '-').padEnd(langW)}  ${autoDeploy}`);
        }
        console.log('');
    }
}
RepoList.description = 'List repositories connected to your Flui account.';
RepoList.examples = [
    '<%= config.bin %> <%= command.id %>',
    '<%= config.bin %> <%= command.id %> --output json',
];
RepoList.flags = {
    output: core_1.Flags.string({
        char: 'o',
        description: 'Output format',
        options: ['text', 'json'],
        default: 'text',
    }),
};
exports.default = RepoList;
