const express = require('express');
const router = express.Router();
const LogoFetcher = require('../lib/logos');

const logoFetcher = new LogoFetcher();

// Get cache statistics
router.get('/stats', async (req, res) => {
  try {
    const stats = await logoFetcher.getCacheStats();
    res.json(stats);
  } catch (error) {
    console.error('Error getting cache stats:', error);
    res.status(500).json({
      error: 'Failed to get cache stats',
      message: error.message
    });
  }
});

// Clear logo cache
router.delete('/logos', async (req, res) => {
  try {
    await logoFetcher.clearCache();
    res.json({
      success: true,
      message: 'Logo cache cleared'
    });
  } catch (error) {
    console.error('Error clearing cache:', error);
    res.status(500).json({
      error: 'Failed to clear cache',
      message: error.message
    });
  }
});

// Prefetch logos
router.post('/prefetch', async (req, res) => {
  try {
    const { products } = req.body;

    if (!products || !Array.isArray(products)) {
      return res.status(400).json({
        error: 'products array is required'
      });
    }

    const results = {};
    for (const product of products) {
      try {
        await logoFetcher.fetchLogo(product);
        results[product] = 'success';
      } catch (error) {
        results[product] = 'failed';
      }
    }

    res.json({
      success: true,
      results
    });

  } catch (error) {
    console.error('Prefetch error:', error);
    res.status(500).json({
      error: 'Failed to prefetch logos',
      message: error.message
    });
  }
});

module.exports = router;
