import { Router, Request, Response } from 'express';
import { generateQRCodeBuffer } from '../utils/qrcode';

// Public QR image endpoint — encodes the visitor's shortId so the resulting
// PNG can be scanned at reception. No auth: the shortId itself is the only
// piece of state the QR carries, and anyone who knows it could already
// impersonate the pass at reception (same risk surface as the QR PNG we
// attach to invite emails). Lets WhatsApp messages link to a viewable QR
// instead of trying to render an inline attachment.

const router = Router();

router.get('/:shortId.png', async (req: Request, res: Response) => {
  try {
    const shortId = (req.params.shortId || '').toString().replace(/[^A-Za-z0-9_-]/g, '');
    if (!shortId) {
      res.status(400).json({ error: 'Bad shortId' });
      return;
    }
    const buf = await generateQRCodeBuffer(shortId);
    res.setHeader('Content-Type', 'image/png');
    res.setHeader('Cache-Control', 'public, max-age=604800'); // 7 days
    res.send(buf);
  } catch (err) {
    console.error('publicQr error', err);
    res.status(500).json({ error: 'Failed to render QR' });
  }
});

export default router;
