import { cache, cacheKeys, cacheTTL } from './cache';

/**
 * Cache management utilities for development and production
 */
export class CacheManager {
  /**
   * Preload critical home page data
   */
  static async preloadHomePageData() {
    try {
      console.log('Preloading home page data...');
      
      // Preload categories (most stable data)
      if (!cache.has(cacheKeys.categories())) {
        const categoriesResponse = await fetch('/api/categories');
        if (categoriesResponse.ok) {
          const categories = await categoriesResponse.json();
          cache.set(cacheKeys.categories(), categories, { ttl: cacheTTL.categories });
        }
      }
      
      // Preload featured products
      if (!cache.has(cacheKeys.featuredProducts())) {
        const productsResponse = await fetch('/api/products?limit=12');
        if (productsResponse.ok) {
          const products = await productsResponse.json();
          cache.set(cacheKeys.featuredProducts(), products, { ttl: cacheTTL.products });
        }
      }
      
      console.log('Home page data preloaded successfully');
    } catch (error) {
      console.warn('Failed to preload home page data:', error);
    }
  }

  /**
   * Warm up cache with commonly accessed data
   */
  static async warmCache() {
    const commonRequests = [
      { key: cacheKeys.categories(), url: '/api/categories', ttl: cacheTTL.categories },
      { key: cacheKeys.products({}), url: '/api/products?limit=20', ttl: cacheTTL.products },
      { key: cacheKeys.products({ page: 2 }), url: '/api/products?page=2', ttl: cacheTTL.products },
    ];

    const warmupPromises = commonRequests.map(async ({ key, url, ttl }) => {
      if (!cache.has(key)) {
        try {
          const response = await fetch(url);
          if (response.ok) {
            const data = await response.json();
            cache.set(key, data, { ttl });
          }
        } catch (error) {
          console.warn(`Failed to warm cache for ${url}:`, error);
        }
      }
    });

    await Promise.allSettled(warmupPromises);
    console.log('Cache warmup completed');
  }

  /**
   * Cache performance analytics
   */
  static getAnalytics() {
    const stats = cache.getStats();
    const performance = {
      cacheSize: stats.totalSize,
      totalItems: stats.totalItems,
      averageItemSize: stats.totalItems > 0 ? stats.totalSize / stats.totalItems : 0,
      memoryUsage: (stats.totalSize / (1024 * 1024)).toFixed(2) + ' MB',
    };

    return performance;
  }

  /**
   * Cache health check
   */
  static healthCheck() {
    const stats = cache.getStats();
    const health = {
      status: 'healthy',
      issues: [] as string[],
      recommendations: [] as string[],
    };

    // Check cache size
    if (stats.totalSize > 5 * 1024 * 1024) { // 5MB
      health.issues.push('Cache size is large (>5MB)');
      health.recommendations.push('Consider reducing cache TTL or clearing old entries');
    }

    // Check item count
    if (stats.totalItems > 50) {
      health.issues.push('High number of cached items');
      health.recommendations.push('Monitor cache performance and consider cleanup');
    }

    if (health.issues.length > 0) {
      health.status = 'warning';
    }

    return health;
  }

  /**
   * Smart cache cleanup
   */
  static smartCleanup() {
    const beforeStats = cache.getStats();
    
    // Clear cache if it's too large
    if (beforeStats.totalSize > 10 * 1024 * 1024) { // 10MB
      cache.clear();
      console.log('Cache cleared due to size limit');
      return;
    }

    // Could implement more sophisticated cleanup logic here
    // For now, rely on automatic TTL cleanup
    console.log('Cache within healthy limits, no cleanup needed');
  }

  /**
   * Export cache data for debugging
   */
  static exportCacheData() {
    const keys = Object.keys(localStorage).filter(key => key.startsWith('cache_'));
    const exportData: Record<string, unknown> = {};

    keys.forEach(key => {
      try {
        const item = localStorage.getItem(key);
        if (item) {
          exportData[key] = JSON.parse(item);
        }
      } catch (error) {
        console.warn(`Failed to export cache item ${key}:`, error);
      }
    });

    return exportData;
  }

  /**
   * Import cache data (for debugging/testing)
   */
  static importCacheData(data: Record<string, unknown>) {
    Object.entries(data).forEach(([key, value]) => {
      try {
        localStorage.setItem(key, JSON.stringify(value));
      } catch (error) {
        console.warn(`Failed to import cache item ${key}:`, error);
      }
    });
  }
}

// Auto-initialize cache management
if (typeof window !== 'undefined') {
  // Preload critical data on page load
  window.addEventListener('load', () => {
    // Delay to avoid blocking initial render
    setTimeout(() => {
      CacheManager.preloadHomePageData();
    }, 2000);
  });

  // Periodic health checks in development
  if (process.env.NODE_ENV === 'development') {
    setInterval(() => {
      const health = CacheManager.healthCheck();
      if (health.status !== 'healthy') {
        console.warn('Cache health issues:', health);
      }
    }, 60000); // Every minute
  }

  // Make cache manager available globally for debugging
  (window as { CacheManager?: typeof CacheManager }).CacheManager = CacheManager;
}