import { Keyv } from 'keyv';
import KeyvRedis from '@keyv/redis';
import type { CacheModuleAsyncOptions } from '@nestjs/cache-manager';
import { ConfigService } from '@nestjs/config';
import { CacheableMemory } from 'cacheable';

export function cacheConfig(): CacheModuleAsyncOptions {
  return {
    isGlobal: true,
    inject: [ConfigService],
    useFactory: async (configService: ConfigService) => {
      const redisUri = configService.get('REDIS_URI');
      const namespace = configService.get('CACHE_NAMESPACE', 'app-cache');
      const ttl = +configService.get<number>('CACHE_TTL', 3600); //1 hour

      return {
        stores: [
          new Keyv({
            store: new CacheableMemory({ ttl: ttl * 1000, lruSize: 5000 }),
            namespace: namespace
          }),
          new KeyvRedis(redisUri, { namespace: namespace }),
        ],
      };
    },
  };
}