import { DynamicModule, Global, Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserWallets } from './user_wallets.entity';
import { WalletTransactions } from './wallet_transactions.entity';
import { UserWalletsMemoryService } from './user_wallets_memory.service';
import { UserWalletsService } from './user_wallets.service';

@Global()
@Module({})
export class UserWalletsModule {
  static forDatabase(): DynamicModule {
    return {
      module: UserWalletsModule,
      imports: [TypeOrmModule.forFeature([UserWallets, WalletTransactions])],
      providers: [
        UserWalletsService,
        {
          provide: 'IUserWalletsService',
          useClass: UserWalletsService,
        },
      ],
      exports: [UserWalletsService, 'IUserWalletsService'],
    };
  }

  static forMemory(): DynamicModule {
    return {
      module: UserWalletsModule,
      providers: [
        UserWalletsMemoryService,
        {
          provide: 'IUserWalletsService',
          useClass: UserWalletsMemoryService,
        },
      ],
      exports: [UserWalletsMemoryService, 'IUserWalletsService'],
    };
  }

  static forRoot(useMemory?: boolean): DynamicModule {
    const shouldUseMemory = useMemory ?? (
      process.env.NODE_ENV === 'test' ||
      process.env.USE_MEMORY_STORAGE === 'true' ||
      !process.env.DB_HOST
    );

    return shouldUseMemory ? this.forMemory() : this.forDatabase();
  }
}
