const axios = require('axios');
const blogAutomationService = require('../services/blogAutomationService');

// Simple in-memory cache to prevent hitting RSS feeds on every request
let newsCache = {
    data: [],
    lastUpdated: 0,
    TTL: 60 * 60 * 1000 // 1 Hour
};

const getFeed = async (req, res) => {
    try {
        const now = Date.now();
        
        // Serve from cache if valid
        if (newsCache.data.length > 0 && (now - newsCache.lastUpdated) < newsCache.TTL) {
            return res.json(newsCache.data);
        }

        console.log('Fetching fresh news feed for API...');
        const newsItems = await blogAutomationService.getTrendingCandidates();

        if (newsItems) {
            newsCache.data = newsItems;
            newsCache.lastUpdated = now;
            return res.json(newsItems);
        } else {
            // If fetch fails but we have old cache, return it with warning header
            if (newsCache.data.length > 0) {
                res.set('X-Warning', 'Stale Data');
                return res.json(newsCache.data);
            }
            return res.status(404).json({ message: 'No news available at the moment.' });
        }

    } catch (error) {
        console.error('Error in getFeed:', error);
        res.status(500).json({ message: 'Failed to fetch news feed' });
    }
};

const getProxy = async (req, res) => {
    const { url } = req.query;

    if (!url) {
        return res.status(400).json({ message: 'URL is required' });
    }

    // Security: Allow only specific domains if needed, or open proxy.
    // For this specific use case, the user wants to proxy 'social.cyware.com'.
    // We can be permissive or strict. Let's be permissive for now but validate it's a URL.
    try {
        new URL(url); // Validate URL format
    } catch (e) {
        return res.status(400).json({ message: 'Invalid URL format' });
    }

    try {
        const response = await axios.get(url, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
        });

        // Forward the content type (JSON or HTML)
        res.set('Content-Type', response.headers['content-type']);
        res.send(response.data);

    } catch (error) {
        console.error(`Proxy Error for ${url}:`, error.message);
        if (error.response) {
            res.status(error.response.status).json({ message: 'Error fetching external resource', details: error.message });
        } else {
            res.status(500).json({ message: 'Server error fetching external resource' });
        }
    }
};

module.exports = { getProxy, getFeed };
