const browser = require('../browser');

module.exports = async ({ selector, attributes = [] }) => {
  if (!selector) {
    throw new Error('Selector é obrigatório');
  }

  await browser.start();
  const p = await browser.ensurePage();

  const attrsStr = JSON.stringify(Array.isArray(attributes) ? attributes : []);

  const elements = await p.evaluate((sel) => {
    const attrs = JSON.parse(sel.__attrs);
    const els = Array.from(document.querySelectorAll(sel.__sel));

    return els.map(el => {
      const data = {
        text: (el.innerText || el.textContent || '').trim()
      };

      for (let i = 0; i < attrs.length; i++) {
        data[attrs[i]] = el.getAttribute(attrs[i]);
      }

      return data;
    });
  }, { __sel: selector, __attrs: attrsStr });

  return {
    success: true,
    action: "extract_elements",
    count: elements.length,
    elements
  };
};
