import { Global, Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../database/prisma.service';
import { QueueService, QUEUE_AI_ANALYSIS, QUEUE_AUDIT_LOG, QUEUE_FILE_CLEANUP, QUEUE_DOCUMENT_IMPORT, QUEUE_NOTIFICATION, QUEUE_DOMAIN_EVENTS, QUEUE_AI_INTERACTIVE, QUEUE_AI_BACKGROUND } from './queue.service';

@Global()
@Module({
  imports: [
    BullModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        const url = config.get<string>('redis.url');
        if (url) {
          return { connection: { url } };
        }
        return {
          connection: {
            host: config.get<string>('redis.host', 'localhost'),
            port: config.get<number>('redis.port', 6379),
            password: config.get<string>('redis.password'),
            db: config.get<number>('redis.db', 0),
          },
        };
      },
    }),
    BullModule.registerQueue(
      { name: QUEUE_AI_ANALYSIS },
      { name: QUEUE_DOCUMENT_IMPORT },
      { name: QUEUE_NOTIFICATION },
      { name: QUEUE_DOMAIN_EVENTS },
      { name: QUEUE_AUDIT_LOG },
      { name: QUEUE_FILE_CLEANUP },
      { name: QUEUE_AI_INTERACTIVE },
      { name: QUEUE_AI_BACKGROUND },
    ),
  ],
  providers: [QueueService, PrismaService],
  exports: [QueueService, BullModule],
})
export class QueueModule {}
