import { Module, Global, OnModuleDestroy } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import Redis from "ioredis";

@Global()
@Module({
  providers: [
    {
      provide: "REDIS_CLIENT",
      useFactory: (configService: ConfigService) => {
        const redisUrl = configService.get<string>("REDIS_URL", "redis://localhost:6379");
        return new Redis(redisUrl);
      },
      inject: [ConfigService],
    },
    {
      provide: "REDIS_SHUTDOWN",
      useFactory: (client: Redis) => {
        return {
          async onModuleDestroy() {
            try {
              await client.quit();
            } catch {
              client.disconnect();
            }
          },
        } as OnModuleDestroy;
      },
      inject: ["REDIS_CLIENT"],
    },
  ],
  exports: ["REDIS_CLIENT"],
})
export class RedisModule {}
