"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 api_client_1 = require("../../lib/api-client");
const config_storage_1 = require("../../lib/config-storage");
class TemplateUse extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(TemplateUse);
        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 apiClient = new api_client_1.ApiClient({ baseUrl: apiUrl, apiKey: apiKey });
        console.log(chalk_1.default.cyan(`\n  Creating ${args.framework} app: ${args.name}\n`));
        // ── Step 1: create repo from template ─────────────────────────────────
        const createSpinner = (0, ora_1.default)('Creating repository from template…').start();
        let repo;
        try {
            repo = await apiClient.post(`/templates/${args.framework}/use`, {
                name: args.name,
                ...(flags.org ? { owner: flags.org } : {}),
                ...(flags.description ? { description: flags.description } : {}),
                private: !flags.public,
            });
            if (repo.alreadyExisted) {
                createSpinner.warn(`Repository ${repo.fullName} already existed — using it`);
            }
            else {
                createSpinner.succeed(`Repository created: ${chalk_1.default.bold(repo.fullName)}`);
            }
        }
        catch (error) {
            createSpinner.fail('Failed to create repository');
            const msg = error.response?.data?.message ?? error.message;
            console.log(chalk_1.default.red(`\n  Error: ${msg}\n`));
            this.exit(1);
        }
        // ── Step 2: auto-import into Flui ──────────────────────────────────────
        if (!flags['no-import']) {
            const importSpinner = (0, ora_1.default)('Connecting repository to Flui…').start();
            try {
                const result = await apiClient.post('/repositories/import', { repositoryIds: [repo.fullName] });
                if (result.errors?.length > 0) {
                    importSpinner.warn(`Repository created but connection had issues: ${result.errors.join(', ')}`);
                }
                else if (result.skipped > 0) {
                    importSpinner.succeed('Repository was already connected to Flui');
                }
                else {
                    importSpinner.succeed('Repository connected to Flui');
                }
            }
            catch (error) {
                importSpinner.warn('Could not auto-connect repository — connect it manually from the dashboard');
                this.warn(error.response?.data?.message ?? error.message);
            }
        }
        // ── Summary ────────────────────────────────────────────────────────────
        console.log('');
        console.log(`  ${chalk_1.default.bold('Repo:')}   ${chalk_1.default.cyan(repo.htmlUrl)}`);
        console.log(`  ${chalk_1.default.bold('Clone:')}  ${repo.cloneUrl}`);
        console.log('');
        console.log(chalk_1.default.dim('  Next steps:'));
        console.log(chalk_1.default.dim(`    git clone ${repo.cloneUrl}`));
        console.log(chalk_1.default.dim(`    cd ${args.name}`));
        console.log(chalk_1.default.dim(`    # Edit flui.yaml as needed`));
        console.log(chalk_1.default.dim(`    flui deploy`));
        console.log('');
    }
}
TemplateUse.description = 'Create a new GitHub repository from a Flui framework template and connect it to your account.';
TemplateUse.examples = [
    '<%= config.bin %> <%= command.id %> astro my-astro-site',
    '<%= config.bin %> <%= command.id %> nextjs my-app --public',
    '<%= config.bin %> <%= command.id %> nestjs my-api --org my-org',
];
TemplateUse.args = {
    framework: core_1.Args.string({
        description: 'Framework template to use (e.g. astro, nextjs, nestjs)',
        required: true,
    }),
    name: core_1.Args.string({
        description: 'Name for the new GitHub repository',
        required: true,
    }),
};
TemplateUse.flags = {
    org: core_1.Flags.string({
        description: 'GitHub organisation or user to create the repo under (default: your account)',
    }),
    description: core_1.Flags.string({
        char: 'd',
        description: 'Repository description',
    }),
    public: core_1.Flags.boolean({
        description: 'Create as a public repository (default: private)',
        default: false,
    }),
    'no-import': core_1.Flags.boolean({
        description: 'Skip auto-importing the repository into Flui',
        default: false,
    }),
};
exports.default = TemplateUse;
