import { Module, Global, forwardRef } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { PrismaModule } from './persistence/prisma/prisma.module';
import {
  PrismaUserRepository,
  PrismaSyncedLegacyUserRepository,
  PrismaRefreshTokenRepository,
  PrismaSmsVerificationRepository,
  PrismaCapabilityRepository,
} from './persistence/repositories';
import { LegacyUserCdcConsumer, WalletAddressCdcConsumer } from './messaging/cdc';
import { KafkaModule, KafkaProducerService } from './kafka';
import { RedisService } from './redis';
import {
  USER_REPOSITORY,
  SYNCED_LEGACY_USER_REPOSITORY,
  REFRESH_TOKEN_REPOSITORY,
  SMS_VERIFICATION_REPOSITORY,
  CAPABILITY_REPOSITORY,
} from '@/domain';
import { ApplicationModule } from '@/application/application.module';

@Global()
@Module({
  imports: [ConfigModule, PrismaModule, KafkaModule, forwardRef(() => ApplicationModule)],
  providers: [
    // CDC
    LegacyUserCdcConsumer,
    WalletAddressCdcConsumer,

    // Kafka Producer
    KafkaProducerService,

    // Redis
    {
      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', 14),
      }),
      inject: [ConfigService],
    },
    RedisService,

    // Repositories
    {
      provide: USER_REPOSITORY,
      useClass: PrismaUserRepository,
    },
    {
      provide: SYNCED_LEGACY_USER_REPOSITORY,
      useClass: PrismaSyncedLegacyUserRepository,
    },
    {
      provide: REFRESH_TOKEN_REPOSITORY,
      useClass: PrismaRefreshTokenRepository,
    },
    {
      provide: SMS_VERIFICATION_REPOSITORY,
      useClass: PrismaSmsVerificationRepository,
    },
    {
      provide: CAPABILITY_REPOSITORY,
      useClass: PrismaCapabilityRepository,
    },
  ],
  exports: [
    PrismaModule,
    KafkaProducerService,
    RedisService,
    USER_REPOSITORY,
    SYNCED_LEGACY_USER_REPOSITORY,
    REFRESH_TOKEN_REPOSITORY,
    SMS_VERIFICATION_REPOSITORY,
    CAPABILITY_REPOSITORY,
  ],
})
export class InfrastructureModule {}
