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 { BlockchainRepository } from './persistence/repositories/blockchain.repository';
import { OutboxRepository } from './persistence/repositories/outbox.repository';
import { RedisService } from './redis/redis.service';
import { KafkaProducerService } from './kafka/kafka-producer.service';
import { KavaBlockchainService } from './blockchain/kava-blockchain.service';

@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,
            },
          },
        }),
        inject: [ConfigService],
      },
    ]),
  ],
  providers: [
    // Repositories
    SystemAccountRepository,
    PoolAccountRepository,
    UserWalletRepository,
    RegionRepository,
    BlockchainRepository,
    OutboxRepository,
    // Services
    KafkaProducerService,
    KavaBlockchainService,
    {
      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,
    BlockchainRepository,
    OutboxRepository,
    // Services
    KafkaProducerService,
    KavaBlockchainService,
    RedisService,
    ClientsModule,
  ],
})
export class InfrastructureModule {}
