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

async function scrapeAmazon(query, browser) {
  const page = await browser.newPage();
  const url = `https://www.amazon.es/s?k=${encodeURIComponent(query)}`;
  
  try {
    await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
    
    const products = await page.evaluate(() => {
      const results = [];
      const cards = document.querySelectorAll('[data-component-type="s-search-result"]');
      
      cards.forEach(card => {
        const titleEl = card.querySelector('h2 a span');
        const priceWhole = card.querySelector('.a-price-whole');
        const priceFraction = card.querySelector('.a-price-fraction');
        const symbolEl = card.querySelector('.a-price-symbol');
        const linkEl = card.querySelector('h2 a');
        
        if (titleEl && priceWhole) {
          const price = `${priceWhole.innerText.trim()}${priceFraction ? priceFraction.innerText.trim() : ''} ${symbolEl ? symbolEl.innerText.trim() : '€'}`;
          results.push({
            name: titleEl.innerText.trim(),
            price: price,
            link: linkEl ? linkEl.href : null,
            source: 'Amazon'
          });
        }
      });
      return results.slice(0, 5);
    });

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

module.exports = scrapeAmazon;
