#!/usr/bin/env node
"use strict";
/**
 * Background Worker for Cluster Operations
 *
 * This script runs as a detached background process to execute
 * long-running cluster operations asynchronously.
 *
 * Usage:
 *   node cluster-worker.js create-cluster '{"clusterId":"...","operationId":"..."}'
 */
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@nestjs/core");
const common_1 = require("@nestjs/common");
const cli_module_1 = require("../cli.module");
const cli_cluster_creator_service_1 = require("../services/cli-cluster-creator.service");
const cli_cluster_repository_1 = require("../lib/repositories/cli-cluster.repository");
const cli_operation_repository_1 = require("../lib/repositories/cli-operation.repository");
const cli_logger_service_1 = require("../services/cli-logger.service");
const logger = new common_1.Logger('ClusterWorker');
async function main() {
    const args = process.argv.slice(2);
    if (args.length < 2) {
        console.error('Usage: cluster-worker <jobType> <jobDataJson>');
        process.exit(1);
    }
    const jobType = args[0];
    const jobDataJson = args[1];
    logger.log(`Starting background worker: ${jobType}`);
    // Bootstrap NestJS application context
    const app = await core_1.NestFactory.createApplicationContext(cli_module_1.CliModule, {
        logger: ['error', 'warn', 'log'],
    });
    try {
        const jobData = JSON.parse(jobDataJson);
        if (jobType === 'create-cluster') {
            await handleCreateCluster(app, jobData);
        }
        else if (jobType === 'delete-cluster') {
            await handleDeleteCluster(app, jobData);
        }
        else {
            throw new Error(`Unknown job type: ${jobType}`);
        }
        logger.log(`Background worker completed successfully: ${jobType}`);
        process.exit(0);
    }
    catch (error) {
        logger.error(`Background worker failed: ${error.message}`, error.stack);
        process.exit(1);
    }
    finally {
        await app.close();
    }
}
async function handleCreateCluster(app, jobData) {
    const { clusterId, operationId } = jobData;
    logger.log(`Creating cluster ${clusterId} (operation ${operationId})`);
    const clusterRepo = app.get(cli_cluster_repository_1.CliClusterRepository);
    const operationRepo = app.get(cli_operation_repository_1.CliOperationRepository);
    const creatorService = app.get(cli_cluster_creator_service_1.CliClusterCreatorService);
    const loggerService = app.get(cli_logger_service_1.CliLoggerService);
    // Load cluster and operation from file storage
    const cluster = await clusterRepo.findOne({ where: { id: clusterId } });
    const operation = await operationRepo.findOne({ where: { id: operationId } });
    if (!cluster) {
        throw new Error(`Cluster ${clusterId} not found`);
    }
    if (!operation) {
        throw new Error(`Operation ${operationId} not found`);
    }
    loggerService.writeLog(operationId, `Background worker started for cluster ${cluster.name}`, 'INFO');
    try {
        // Execute cluster creation synchronously (within this background process)
        await creatorService.createClusterSync(cluster, operation);
        loggerService.writeLog(operationId, `Cluster ${cluster.name} created successfully`, 'INFO');
    }
    catch (error) {
        loggerService.writeLog(operationId, `Cluster creation failed: ${error.message}`, 'ERROR');
        throw error;
    }
}
async function handleDeleteCluster(app, jobData) {
    const { clusterId } = jobData;
    logger.log(`Deleting cluster ${clusterId}`);
    // TODO: Implement background cluster deletion if needed
    throw new Error('Background cluster deletion not yet implemented');
}
// Run main function
main();
