const express = require('express');
const router = express.Router();
const { authenticate } = require('../middleware/auth');
const { modifyLimiter } = require('../middleware/rateLimiter');
const { cacheAllLogos, cleanupOldLogos } = require('../jobs/logoCacher');
const { db } = require('../database/db');

// Trigger logo caching (admin only)
router.post('/cache', authenticate, modifyLimiter, async (req, res) => {
  try {
    // Run caching in background
    cacheAllLogos().catch(err => {
      console.error('[LogoCache API] Background caching error:', err);
    });
    
    res.json({ message: 'Logo caching started in background' });
  } catch (error) {
    console.error('[LogoCache API] Error starting cache:', error);
    res.status(500).json({ error: 'Failed to start logo caching' });
  }
});

// Get cache status
router.get('/status', authenticate, async (req, res) => {
  try {
    const stats = await new Promise((resolve, reject) => {
      db.get(
        `SELECT 
          COUNT(*) as cached_count,
          (SELECT COUNT(*) FROM channels WHERE logo LIKE 'http%' OR custom_logo LIKE 'http%') as total_count
         FROM logo_cache`,
        [],
        (err, row) => {
          if (err) reject(err);
          else resolve(row);
        }
      );
    });
    
    res.json(stats);
  } catch (error) {
    console.error('[LogoCache API] Error getting status:', error);
    res.status(500).json({ error: 'Failed to get cache status' });
  }
});

// Cleanup old cached logos
router.post('/cleanup', authenticate, modifyLimiter, async (req, res) => {
  try {
    await cleanupOldLogos();
    res.json({ message: 'Old logos cleaned up successfully' });
  } catch (error) {
    console.error('[LogoCache API] Cleanup error:', error);
    res.status(500).json({ error: 'Failed to cleanup logos' });
  }
});

module.exports = router;
