import { Module, Global } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { PrismaModule } from './persistence/prisma/prisma.module';
import { SystemAccountRepository } from './persistence/repositories/system-account.repository';
import { PoolAccountRepository } from './persistence/repositories/pool-account.repository';
import { UserWalletRepository } from './persistence/repositories/user-wallet.repository';
import { RegionRepository } from './persistence/repositories/region.repository';
import { OutboxRepository } from './persistence/repositories/outbox.repository';
import { ProcessedEventRepository } from './persistence/repositories/processed-event.repository';
import { RedisService } from './redis/redis.service';
import { KafkaProducerService } from './kafka/kafka-producer.service';
// 注意: Consumers 移到 ApplicationModule 中，因为它们依赖应用服务

@Global()
@Module({
  imports: [
    PrismaModule,
    ClientsModule.registerAsync([
      {
        name: 'KAFKA_CLIENT',
        imports: [ConfigModule],
        useFactory: (configService: ConfigService) => ({
          transport: Transport.KAFKA,
          options: {
            client: {
              clientId: 'mining-wallet-service',
              brokers: configService
                .get<string>('KAFKA_BROKERS', 'localhost:9092')
                .split(','),
            },
            producer: {
              allowAutoTopicCreation: true,
            },
            consumer: {
              groupId: 'mining-wallet-service-group',
            },
          },
        }),
        inject: [ConfigService],
      },
    ]),
  ],
  providers: [
    // Repositories
    SystemAccountRepository,
    PoolAccountRepository,
    UserWalletRepository,
    RegionRepository,
    OutboxRepository,
    ProcessedEventRepository,
    // Services
    KafkaProducerService,
    // Consumers 已移到 ApplicationModule
    {
      provide: 'REDIS_OPTIONS',
      useFactory: (configService: ConfigService) => ({
        host: configService.get<string>('REDIS_HOST', 'localhost'),
        port: configService.get<number>('REDIS_PORT', 6379),
        password: configService.get<string>('REDIS_PASSWORD'),
        db: configService.get<number>('REDIS_DB', 15),
      }),
      inject: [ConfigService],
    },
    RedisService,
  ],
  exports: [
    // Repositories
    SystemAccountRepository,
    PoolAccountRepository,
    UserWalletRepository,
    RegionRepository,
    OutboxRepository,
    ProcessedEventRepository,
    // Services
    KafkaProducerService,
    RedisService,
    ClientsModule,
  ],
})
export class InfrastructureModule {}
