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 { MiningAccountRepository } from './persistence/repositories/mining-account.repository';
import { MiningConfigRepository } from './persistence/repositories/mining-config.repository';
import { PriceSnapshotRepository } from './persistence/repositories/price-snapshot.repository';
import { OutboxRepository } from './persistence/repositories/outbox.repository';
import { SystemMiningAccountRepository } from './persistence/repositories/system-mining-account.repository';
import { RedisService } from './redis/redis.service';
import { KafkaProducerService } from './kafka/kafka-producer.service';

@Global()
@Module({
  imports: [
    PrismaModule,
    ClientsModule.registerAsync([
      {
        name: 'KAFKA_CLIENT',
        imports: [ConfigModule],
        useFactory: (configService: ConfigService) => ({
          transport: Transport.KAFKA,
          options: {
            client: {
              clientId: 'mining-service',
              brokers: configService
                .get<string>('KAFKA_BROKERS', 'localhost:9092')
                .split(','),
            },
            producer: {
              allowAutoTopicCreation: true,
            },
          },
        }),
        inject: [ConfigService],
      },
    ]),
  ],
  providers: [
    MiningAccountRepository,
    MiningConfigRepository,
    PriceSnapshotRepository,
    OutboxRepository,
    SystemMiningAccountRepository,
    KafkaProducerService,
    {
      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', 16),
      }),
      inject: [ConfigService],
    },
    RedisService,
  ],
  exports: [
    MiningAccountRepository,
    MiningConfigRepository,
    PriceSnapshotRepository,
    OutboxRepository,
    SystemMiningAccountRepository,
    KafkaProducerService,
    RedisService,
    ClientsModule,
  ],
})
export class InfrastructureModule {}
