const fs = require('fs');
const puppeteer = require('puppeteer');
const { screenshotConfig } = require('../config/config');

/**
 * Check if screenshot files exist
 * @param {Array} filenames - Array of filenames to check
 * @returns {Boolean}
 */
function checkScreenshotsExist(filenames) {
  return filenames.every(filename => 
    fs.existsSync(screenshotConfig.outputDir + filename)
  );
}

/**
 * Generate screenshots using Puppeteer
 * @param {String} url - URL to capture
 * @param {Array} clipConfigs - Array of clip configurations {filename, clip}
 * @param {Object} options - Additional options (viewport, waitTime)
 * @returns {Promise}
 */
async function generateScreenshots(url, clipConfigs, options = {}) {
  const viewport = options.viewport || {
    width: screenshotConfig.viewportWidth,
    height: screenshotConfig.viewportHeight
  };
  const waitTime = options.waitTime || screenshotConfig.waitTime;

  const browser = await puppeteer.launch({
    headless: true,
    args: screenshotConfig.puppeteerArgs
  });

  try {
    const page = await browser.newPage();
    
    page.on('load', () => {
      console.log('Page load event fired');
    });

    await page.setViewport(viewport);
    
    await page.goto(url, {
      waitUntil: 'domcontentloaded',
      waitLoad: true,
      waitNetworkIdle: true
    });
    
    await page.waitFor(waitTime);

    // Capture all screenshots
    for (const config of clipConfigs) {
      await page.screenshot({
        path: screenshotConfig.outputDir + config.filename,
        clip: config.clip
      });
    }

    console.log('Screenshots generated successfully');
  } finally {
    await browser.close();
    console.log('Browser closed');
  }
}

/**
 * Build response payload with thumbnail URLs
 * @param {Object} filenames - Object with thumbnail filename properties
 * @returns {Object}
 */
function buildResponsePayload(filenames) {
  const payload = { time: new Date().toISOString() };
  
  for (const [key, filename] of Object.entries(filenames)) {
    payload[key] = screenshotConfig.baseUrl + filename;
  }
  
  return payload;
}

module.exports = {
  checkScreenshotsExist,
  generateScreenshots,
  buildResponsePayload
};
