import { Logger } from '@nestjs/common';
import type { INestApplicationContext } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { WorkerModule } from './worker.module';

let appContext: INestApplicationContext | null = null;
let keepAliveTimer: NodeJS.Timeout | null = null;

async function shutdown() {
  if (keepAliveTimer) {
    clearInterval(keepAliveTimer);
    keepAliveTimer = null;
  }
  await appContext?.close();
  process.exit(0);
}

async function bootstrap() {
  const logger = new Logger('AutomationWorker');
  appContext = await NestFactory.createApplicationContext(WorkerModule);
  appContext.enableShutdownHooks();
  keepAliveTimer = setInterval(() => {
    // Keep the standalone worker process alive between BullMQ jobs.
  }, 60_000);
  logger.log('Automation worker started');
}

void bootstrap();

process.once('SIGINT', () => void shutdown());
process.once('SIGTERM', () => void shutdown());
