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

/**
 * All-Over Print Mask screenshot handler (single front view)
 * Route: GET /mask/:designId
 */
router.get('/:designId', async (req, res) => {
  try {
    const designId = req.params.designId;
    console.log('All-Over Print Mask screenshot request for design:', designId);

    const filenames = {
      thumb_front: `${designId}-front-thumbnail.png`
    };

    // Check if screenshot already exists
    if (checkScreenshotsExist(Object.values(filenames))) {
      console.log('Screenshot already exists, returning cached version');
      return res.status(200).jsonp(buildResponsePayload(filenames));
    }

    // Generate new screenshot
    const url = `${viewerUrls.crewsportswear}${designId}/`;
    const clipConfigs = [
      {
        filename: filenames.thumb_front,
        clip: { x: 0, y: 0, width: 635, height: 600 }
      }
    ];

    await generateScreenshots(url, clipConfigs);

    res.status(200).jsonp(buildResponsePayload(filenames));
  } catch (error) {
    console.error('All-Over Print Mask screenshot error:', error);
    res.status(500).json({ 
      error: 'Failed to generate screenshot',
      message: error.message 
    });
  }
});

/**
 * Classic Mask screenshot handler (single front view with larger dimensions)
 * Route: GET /mask/classic/:designId
 */
router.get('/classic/:designId', async (req, res) => {
  try {
    const designId = req.params.designId;
    console.log('Classic Mask screenshot request for design:', designId);

    const filenames = {
      thumb_front: `${designId}-front-thumbnail.png`
    };

    // Check if screenshot already exists
    if (checkScreenshotsExist(Object.values(filenames))) {
      console.log('Screenshot already exists, returning cached version');
      return res.status(200).jsonp(buildResponsePayload(filenames));
    }

    // Generate new screenshot
    const url = `${viewerUrls.crewsportswear}${designId}/`;
    const clipConfigs = [
      {
        filename: filenames.thumb_front,
        clip: { x: 0, y: 0, width: 710, height: 600 }
      }
    ];

    await generateScreenshots(url, clipConfigs);

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

module.exports = router;
