const express = require('express');
const router = express.Router();
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');

router.get('/setup', (req, res) => {
  const secret = speakeasy.generateSecret({ name: 'Mek-Tech Consulting', length: 32 });
  req.session.tfaSecret = secret.base32;
  
  QRCode.toDataURL(secret.otpauth_url, (err, imageUrl) => {
    if (err) {
      console.error(err);
      return res.status(500).json({ error: 'Failed to generate QR code' });
    }
    res.json({ secret: secret.base32, qrCode: imageUrl });
  });
});

router.post('/verify', (req, res) => {
  const { token, secret } = req.body;
  const verified = speakeasy.totp.verify({
    secret: secret || req.session.tfaSecret,
    encoding: 'base32',
    token: token
  });
  
  if (verified) {
    req.session.tfaVerified = true;
    res.json({ success: true });
  } else {
    res.json({ success: false, error: 'Invalid token' });
  }
});

module.exports = router;
