import { DynamicModule, Module, Global } from '@nestjs/common';
import { KafkaConfig, createKafkaConfig } from './kafka.config';
import { KafkaProducerService } from './kafka-producer.service';
import { KafkaConsumerService } from './kafka-consumer.service';

export interface KafkaModuleOptions {
  clientId: string;
  groupId?: string;
  /** Override auto-detected config */
  config?: Partial<KafkaConfig>;
}

/**
 * Global Kafka module for NestJS services.
 * Register once in AppModule with forRoot().
 *
 * Usage:
 *   KafkaModule.forRoot({ clientId: 'user-service', groupId: 'genex-user-service' })
 */
@Global()
@Module({})
export class KafkaModule {
  static forRoot(options: KafkaModuleOptions): DynamicModule {
    const baseConfig = createKafkaConfig(options.clientId, options.groupId);
    const mergedConfig: KafkaConfig = { ...baseConfig, ...options.config };

    const kafkaConfigProvider = {
      provide: 'KAFKA_CONFIG',
      useValue: mergedConfig,
    };

    const producerProvider = {
      provide: KafkaProducerService,
      useFactory: () => new KafkaProducerService(mergedConfig),
    };

    const providers: any[] = [kafkaConfigProvider, producerProvider];
    const exports: any[] = [KafkaProducerService];

    // Only create consumer if groupId is provided
    if (mergedConfig.groupId) {
      const consumerProvider = {
        provide: KafkaConsumerService,
        useFactory: () => new KafkaConsumerService(mergedConfig),
      };
      providers.push(consumerProvider);
      exports.push(KafkaConsumerService);
    }

    return {
      module: KafkaModule,
      providers,
      exports,
    };
  }
}
