import type { AwilixContainer } from 'awilix';
import { NamespacedCache, type CacheProvider } from '@stock-bot/cache';
import type { ServiceDefinitions } from '../container/types';

export class CacheFactory {
  static createNamespacedCache(
    baseCache: CacheProvider,
    namespace: string
  ): NamespacedCache {
    return new NamespacedCache(baseCache, namespace);
  }

  static createCacheForService(
    container: AwilixContainer<ServiceDefinitions>,
    serviceName: string
  ): CacheProvider | null {
    const baseCache = container.cradle.cache;
    if (!baseCache) {return null;}
    
    return this.createNamespacedCache(baseCache, serviceName);
  }

  static createCacheForHandler(
    container: AwilixContainer<ServiceDefinitions>,
    handlerName: string
  ): CacheProvider | null {
    const baseCache = container.cradle.cache;
    if (!baseCache) {return null;}
    
    return this.createNamespacedCache(baseCache, `handler:${handlerName}`);
  }

  static createCacheWithPrefix(
    container: AwilixContainer<ServiceDefinitions>,
    prefix: string
  ): CacheProvider | null {
    const baseCache = container.cradle.cache;
    if (!baseCache) {return null;}
    
    // Remove 'cache:' prefix if already included
    const cleanPrefix = prefix.replace(/^cache:/, '');
    return this.createNamespacedCache(baseCache, cleanPrefix);
  }
}