import { format } from 'date-fns';

/**
 * Shared optimization utilities for report generation.
 * Handles caching, async yielding, and cancellation tokens.
 */

// Simple in-memory cache
const cacheStorage = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

export const getCachedData = (key) => {
  const item = cacheStorage.get(key);
  if (!item) return null;
  
  if (Date.now() > item.expiry) {
    cacheStorage.delete(key);
    return null;
  }
  
  return item.data;
};

export const setCachedData = (key, data, ttl = CACHE_TTL) => {
  cacheStorage.set(key, {
    data,
    expiry: Date.now() + ttl
  });
};

export const clearCache = (keyPattern) => {
  if (!keyPattern) {
    cacheStorage.clear();
    return;
  }
  for (const key of cacheStorage.keys()) {
    if (key.includes(keyPattern)) {
      cacheStorage.delete(key);
    }
  }
};

// Async yielder to prevent UI freezing during heavy loops
export const yieldToMain = () => new Promise(resolve => setTimeout(resolve, 0));

// Canvas-based image compression
export const compressImage = async (img, quality = 0.7, maxWidth = 800) => {
    return new Promise((resolve) => {
        const canvas = document.createElement('canvas');
        let { width, height } = img;

        // Scale down if needed
        if (width > maxWidth) {
            height = Math.round((height * maxWidth) / width);
            width = maxWidth;
        }

        canvas.width = width;
        canvas.height = height;
        
        const ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, width, height);
        
        // Compress
        resolve(canvas.toDataURL('image/jpeg', quality));
    });
};

// Generate cache key helper
export const generateCacheKey = (prefix, params) => {
    return `${prefix}_${JSON.stringify(params)}`;
};
