const { execFile } = require('child_process');
const path = require('path');
const fs = require('fs');

const SCREENSHOTS_DIR = path.join(__dirname, '../public/screenshots');

function takeScreenshot(slug, port, useLocalhost = false) {
  return new Promise((resolve, reject) => {
    const outPath = path.join(SCREENSHOTS_DIR, `${slug}.png`);
    const host = useLocalhost ? 'localhost' : '127.0.0.1';
    const url = `http://${host}:${port}`;

    const args = [
      'screenshot',
      '--viewport-size', '1280,800',
      '--wait-for-timeout', '3000',
      url,
      outPath,
    ];

    execFile('/usr/bin/playwright', args, { timeout: 30000 }, (err, stdout, stderr) => {
      if (err) {
        reject(new Error(`Screenshot failed: ${err.message}\n${stderr}`));
      } else if (fs.existsSync(outPath)) {
        resolve(`/screenshots/${slug}.png`);
      } else {
        reject(new Error('Screenshot file not created'));
      }
    });
  });
}

module.exports = { takeScreenshot };
