const puppeteer = require('puppeteer-extra');

async function scrapeOpenFoodFacts(query, browser) {
  const page = await browser.newPage();
  const url = `https://world.openfoodfacts.org/cgi/search.pl?search_terms=${encodeURIComponent(query)}&search_simple=1&action=process`;
  
  try {
    await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
    
    const products = await page.evaluate(() => {
      const results = [];
      const items = document.querySelectorAll('#search_results li');
      
      items.forEach(item => {
        const linkEl = item.querySelector('a');
        const titleEl = item.querySelector('span:not([class])') || item.querySelector('.list_product_name'); // heuristic
        
        let link = linkEl ? linkEl.href : null;
        if (link && !link.startsWith('http')) {
            link = `https://world.openfoodfacts.org${link}`;
        }
        
        if (linkEl && linkEl.title) {
          results.push({
            name: linkEl.title.trim(),
            price: 'N/A', // OFF usually doesn't have prices
            link: link,
            source: 'OpenFoodFacts'
          });
        }
      });
      return results.slice(0, 5);
    });

    return products;
  } catch (error) {
    console.error(`[OpenFoodFacts] Error scraping ${query}:`, error.message);
    return [];
  } finally {
    await page.close();
  }
}

module.exports = scrapeOpenFoodFacts;
