import { Router } from 'express';
import QRCode from 'qrcode';

const router = Router();

router.get('/', async (req, res, next) => {
  try {
    const text = req.query.text as string;
    if (!text) {
      res.status(400).json({ error: { message: 'text parameter is required' } });
      return;
    }
    if (text.length > 2000) {
      res.status(400).json({ error: { message: 'text parameter must be 2000 characters or fewer' } });
      return;
    }

    const rawSize = parseInt(req.query.size as string, 10);
    const size = Math.min(500, Math.max(50, isNaN(rawSize) ? 200 : rawSize));

    const buffer = await QRCode.toBuffer(text, {
      type: 'png',
      width: size,
      margin: 1,
      errorCorrectionLevel: 'M',
    });

    res.set('Content-Type', 'image/png');
    res.set('Cache-Control', 'public, max-age=3600');
    res.set('Cross-Origin-Resource-Policy', 'cross-origin');
    res.send(buffer);
  } catch (err) {
    next(err);
  }
});

export const qrRouter = router;
