"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNestApp = getNestApp;
exports.closeNestApp = closeNestApp;
exports.getService = getService;
const core_1 = require("@nestjs/core");
const cli_module_1 = require("../cli.module");
const profile_manager_1 = require("./profile-manager");
let appInstance = null;
/**
 * Ensure base .flui directory exists and migrate legacy layout if needed.
 */
function ensureCliDataDir() {
    profile_manager_1.ProfileManager.migrateIfNeeded();
}
/**
 * Get or create NestJS application (singleton)
 * Uses full NestJS application instead of just application context
 * to support TypeORM and Bull which require ModuleRef
 * @returns NestJS application
 */
async function getNestApp() {
    if (!appInstance) {
        // Ensure data directory exists before bootstrap
        ensureCliDataDir();
        // CLI does not use Redis — disable cache unless explicitly enabled
        process.env.CACHE_ENABLED ??= 'false';
        // Create full NestJS application (with HTTP server but we won't listen)
        // This is required for TypeORM and Bull to work properly
        appInstance = await core_1.NestFactory.create(cli_module_1.CliModule, {
            logger: ['error', 'warn'], // Only show errors and warnings
            abortOnError: true, // Exit on errors to see what's wrong
        });
        // Don't call init() - NestFactory.create() already initializes the app
    }
    return appInstance;
}
/**
 * Close NestJS application context and cleanup
 */
async function closeNestApp() {
    if (appInstance) {
        await appInstance.close();
        appInstance = null;
    }
    // process.exit() drops pending async pipe writes — flush first.
    await Promise.all([
        new Promise((resolve) => {
            if (!process.stdout.writable)
                return resolve();
            process.stdout.write('', () => resolve());
        }),
        new Promise((resolve) => {
            if (!process.stderr.writable)
                return resolve();
            process.stderr.write('', () => resolve());
        }),
    ]);
    // Bull/TypeORM keepalive timers prevent natural exit.
    process.exit(process.exitCode ?? 0);
}
/**
 * Get service from NestJS DI container
 * Convenience helper for type-safe service retrieval
 */
async function getService(serviceClass) {
    const app = await getNestApp();
    return app.get(serviceClass);
}
