const express = require('express');
const router = express.Router();
const logger = require('../utils/logger');
const { generateQRCode } = require('../services/qrcode');

// Generate QR code
router.get('/', async (req, res) => {
    try {
        const { text, size = 200 } = req.query;
        
        if (!text) {
            return res.status(400).json({
                success: false,
                error: 'Text parameter is required'
            });
        }
        
        const qrOptions = {
            type: 'png',
            width: parseInt(size),
            margin: 1,
            color: {
                dark: '#000000',
                light: '#FFFFFF'
            },
            errorCorrectionLevel: 'M'
        };
        
        const buffer = await generateQRCode(text, qrOptions);
        
        res.set({
            'Content-Type': 'image/png',
            'Content-Length': buffer.length,
            'Cache-Control': 'public, max-age=3600' // Cache for 1 hour
        });
        
        res.send(buffer);
        
    } catch (error) {
        logger.error('QR code generation error:', error);
        res.status(500).json({
            success: false,
            error: 'Failed to generate QR code'
        });
    }
});

module.exports = router;