const express = require('express');
const router = express.Router();
const { checkScreenshotsExist, generateScreenshots, buildResponsePayload } = require('../utils/screenshot');
const { viewerUrls } = require('../config/config');

/**
 * Jersey screenshot handler (4 views: front, back, right, left)
 * Route: GET /jersey/:designId
 */
router.get('/:designId', async (req, res) => {
  try {
    const designId = req.params.designId;
    console.log('Jersey screenshot request for design:', designId);

    const filenames = {
      thumb_front: `${designId}-front-thumbnail.png`,
      thumb_back: `${designId}-back-thumbnail.png`,
      thumb_right: `${designId}-right-thumbnail.png`,
      thumb_left: `${designId}-left-thumbnail.png`
    };

    // Check if screenshots already exist
    if (checkScreenshotsExist(Object.values(filenames))) {
      console.log('Screenshots already exist, returning cached versions');
      return res.status(200).jsonp(buildResponsePayload(filenames));
    }

    // Generate new screenshots
    const url = `${viewerUrls.crewsportswear}${designId}/`;
    const clipConfigs = [
      {
        filename: filenames.thumb_front,
        clip: { x: 21.64, y: 48.11, width: 666, height: 520 }
      },
      {
        filename: filenames.thumb_back,
        clip: { x: 781.619, y: 48.11, width: 470, height: 520 }
      },
      {
        filename: filenames.thumb_right,
        clip: { x: 119.64, y: 584.407, width: 470, height: 520 }
      },
      {
        filename: filenames.thumb_left,
        clip: { x: 781.619, y: 584.407, width: 470, height: 520 }
      }
    ];

    await generateScreenshots(url, clipConfigs, { waitTime: 6000 });

    res.status(200).jsonp(buildResponsePayload(filenames));
  } catch (error) {
    console.error('Jersey screenshot error:', error);
    res.status(500).json({ 
      error: 'Failed to generate screenshots',
      message: error.message 
    });
  }
});

module.exports = router;
