/**
 * Temporal Worker
 * 
 * 这个文件需要单独运行，用于处理审批工作流
 * 运行命令: npm run start:temporal
 * 
 * 注意: 所有审批相关的 workflows 和 activities 都在 approval/temporal/ 目录下
 */

// 手动注册 tsconfig-paths 以支持路径别名
import * as tsConfigPaths from 'tsconfig-paths';
import * as path from 'path';

// 使用 process.cwd() 获取项目根目录（backend/）
const baseUrl = process.cwd();
console.log('[Worker] Registering tsconfig-paths with baseUrl:', baseUrl);

const cleanup = tsConfigPaths.register({
  baseUrl,
  paths: {
    '@/*': ['src/*'],
    '@core/*': ['src/core/*'],
    '@engines/*': ['src/engines/*'],
    '@modules/*': ['src/modules/*'],
    '@common/*': ['src/common/*'],
  },
});

console.log('[Worker] tsconfig-paths registered successfully');

import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { Worker, NativeConnection } from '@temporalio/worker';
import * as approvalActivities from '@engines/approval/temporal/activities/approval.activities';
import { WorkerModule } from './worker.module';
import { PrismaService } from '@core/database/prisma/prisma.service';
import { NotificationService } from '@core/messaging/notification/notification.service';
import { BusinessTypeRegistry } from '@engines/approval/business-type-registry.service';
import { TemporalLoggerService } from '@core/observability/logging/services/temporal-logger.service';

async function run() {
  console.log('🚀 Starting Temporal Worker...');
  
  // 使用 WorkerModule 而不是 AppModule，避免加载不必要的模块（如定时任务）
  const app = await NestFactory.createApplicationContext(WorkerModule, {
    logger: ['error', 'warn', 'log'], // 只显示重要日志
  });
  const configService = app.get(ConfigService);
  const prismaService = app.get(PrismaService);
  const notificationService = app.get(NotificationService);
  const businessTypeRegistry = app.get(BusinessTypeRegistry);
  const temporalLogger = app.get(TemporalLoggerService);

  // 初始化 activities（注入依赖）
  // TD-6: 传递 BusinessTypeRegistry 以支持业务数据集成
  approvalActivities.initializeActivities(prismaService, notificationService, temporalLogger, businessTypeRegistry);

  // 使用审批引擎的 activities
  const activities = approvalActivities;

  // 连接到 Temporal Server
  const temporalAddress = configService.get('temporal.address') || 'localhost:3033';
  const namespace = configService.get<string>('temporal.namespace') || 'default';
  const connection = await NativeConnection.connect({ address: temporalAddress });

  const taskQueue = configService.get('temporal.taskQueue') || 'ffoa-task-queue';

  const worker = await Worker.create({
    connection,
    namespace,
    workflowsPath: require.resolve('@engines/approval/temporal/workflows'),
    activities,
    taskQueue,
  });

  console.log('');
  console.log('✅ ========================================');
  console.log('✅  Temporal Worker Started Successfully');
  console.log('✅ ========================================');
  console.log(`📋 Task Queue: ${taskQueue}`);
  console.log(`🌐 Temporal Server: ${temporalAddress}`);
  console.log(`🏷️  Namespace: ${namespace}`);
  console.log('🔄 Polling for approval workflow tasks...');
  console.log('');

  await worker.run();
}

run().catch((err) => {
  console.error('Failed to start worker', err);
  process.exit(1);
});

