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

module.exports = async ({ data }) => {
  if (!data) {
    throw new Error('Data é obrigatória');
  }

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

  const result = await p.evaluate((formData) => {
    const inputs = Array.from(document.querySelectorAll('input, textarea, select'));

    let filled = [];

    inputs.forEach(input => {
      const key = Object.keys(formData).find(k =>
        (input.name && input.name.toLowerCase().includes(k.toLowerCase())) ||
        (input.placeholder && input.placeholder.toLowerCase().includes(k.toLowerCase())) ||
        (input.id && input.id.toLowerCase().includes(k.toLowerCase())) ||
        (input.getAttribute('aria-label') || '').toLowerCase().includes(k.toLowerCase())
      );

      if (key) {
        const value = formData[key];

        const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
          window.HTMLInputElement.prototype, 'value'
        )?.set;

        const nativeTextAreaValueSetter = Object.getOwnPropertyDescriptor(
          window.HTMLTextAreaElement.prototype, 'value'
        )?.set;

        if (input.tagName === 'INPUT' && nativeInputValueSetter) {
          nativeInputValueSetter.call(input, value);
        } else if (input.tagName === 'TEXTAREA' && nativeTextAreaValueSetter) {
          nativeTextAreaValueSetter.call(input, value);
        } else {
          input.value = value;
        }

        input.dispatchEvent(new Event('input', { bubbles: true }));
        input.dispatchEvent(new Event('change', { bubbles: true }));

        filled.push({
          field: input.name || input.id || input.placeholder || 'unknown',
          value: value
        });
      }
    });

    return filled;
  }, data);

  return {
    success: true,
    action: "fill_form_auto",
    filled: result,
    count: result.length
  };
};
