import { asFunction, asValue, type AwilixContainer } from 'awilix';
import type { AppConfig } from '../config/schemas';
import type { ServiceDefinitions } from '../container/types';

export function registerCacheServices(
  container: AwilixContainer<ServiceDefinitions>,
  config: AppConfig
): void {
  if (config.redis.enabled) {
    container.register({
      cache: asFunction(({ logger }) => {
        const { createServiceCache } = require('@stock-bot/queue');
        // Get standardized service name from config
        const serviceName = config.service?.serviceName || config.service?.name || 'unknown';
        
        // Create service-specific cache that uses the service's Redis DB
        return createServiceCache(serviceName, {
          host: config.redis.host,
          port: config.redis.port,
          password: config.redis.password,
          db: config.redis.db, // This will be overridden by ServiceCache
        }, { logger });
      }).singleton(),
      
      // Also provide global cache for shared data
      globalCache: asFunction(({ logger }) => {
        const { createServiceCache } = require('@stock-bot/queue');
        const serviceName = config.service?.serviceName || config.service?.name || 'unknown';
        
        return createServiceCache(serviceName, {
          host: config.redis.host,
          port: config.redis.port,
          password: config.redis.password,
        }, { global: true, logger });
      }).singleton(),
    });
  } else {
    container.register({
      cache: asValue(null),
      globalCache: asValue(null),
    });
  }
}