import { Inject, Injectable, Module, OnModuleDestroy } from '@nestjs/common';
import Redis from 'ioredis';
import { APP_ENVIRONMENT, AppEnvironment } from '../../../configuration/src';

export const REDIS_CLIENT = Symbol('REDIS_CLIENT');

export const redisClientProvider = {
  provide: REDIS_CLIENT,
  inject: [APP_ENVIRONMENT],
  useFactory: (env: AppEnvironment) =>
    new Redis(env.redisUrl, { lazyConnect: false }),
};

@Injectable()
class RedisLifecycle implements OnModuleDestroy {
  constructor(@Inject(REDIS_CLIENT) private readonly client: Redis) {}

  async onModuleDestroy(): Promise<void> {
    await this.client.quit();
  }
}

@Module({
  providers: [redisClientProvider, RedisLifecycle],
  exports: [redisClientProvider],
})
export class RedisModule {}
