const express = require('express');
const router = express.Router();
const ComparisonGenerator = require('../generators/comparison');
const fs = require('fs').promises;
const path = require('path');

const generator = new ComparisonGenerator();

// Generate single comparison image
router.post('/comparison', async (req, res) => {
  try {
    const { productA, productB, style } = req.body;

    if (!productA || !productB) {
      return res.status(400).json({
        error: 'Both productA and productB are required'
      });
    }

    const buffer = await generator.generate(productA, productB, style ? { style } : {});

    res.set('Content-Type', 'image/png');
    res.set('Content-Disposition', `attachment; filename="${productA}-vs-${productB}.png"`);
    res.send(buffer);

  } catch (error) {
    console.error('Generation error:', error);
    res.status(500).json({
      error: 'Failed to generate image',
      message: error.message
    });
  }
});

// Generate batch of comparison images
router.post('/batch', async (req, res) => {
  try {
    const { comparisons } = req.body;

    if (!comparisons || !Array.isArray(comparisons)) {
      return res.status(400).json({
        error: 'comparisons array is required'
      });
    }

    const results = await generator.generateBatch(comparisons);

    // Save to generated folder
    const generatedDir = path.join(__dirname, '../../generated');
    await fs.mkdir(generatedDir, { recursive: true });

    const files = [];
    for (const result of results) {
      const filename = `${result.productA}-vs-${result.productB}.png`;
      const filepath = path.join(generatedDir, filename);
      await fs.writeFile(filepath, result.buffer);
      files.push(filename);
    }

    res.json({
      success: true,
      count: results.length,
      files
    });

  } catch (error) {
    console.error('Batch generation error:', error);
    res.status(500).json({
      error: 'Failed to generate batch',
      message: error.message
    });
  }
});

// Get available styles
router.get('/styles', (req, res) => {
  const styles = require('../config/styles.json');
  res.json(styles);
});

// Get randomization history
router.get('/history', (req, res) => {
  const history = generator.randomizer.getHistory();
  res.json({
    count: history.length,
    history
  });
});

// Clear randomization history
router.delete('/history', (req, res) => {
  generator.randomizer.clearHistory();
  res.json({
    success: true,
    message: 'History cleared'
  });
});

module.exports = router;
