const express = require('express');
const { requireAuth } = require('../middleware/auth');
const { checkGracePeriod } = require('../middleware/gracePeriod');
const { getAlertsForUser, markAlertRead } = require('../services/alertService');

const router = express.Router();

const PAID_TIERS = new Set(['analyst', 'desk']);

router.get('/', requireAuth, checkGracePeriod, async (req, res) => {
  if (!PAID_TIERS.has(req.user.tier)) {
    return res.status(403).json({ error: 'Alerts are available on Analyst and Desk tiers' });
  }

  try {
    const result = await getAlertsForUser(req.user.id);
    return res.json(result);
  } catch (err) {
    console.error('[VYNDR] Alerts error:', err.message);
    return res.status(503).json({ error: 'Alerts temporarily unavailable' });
  }
});

router.patch('/:id/read', requireAuth, checkGracePeriod, async (req, res) => {
  if (!PAID_TIERS.has(req.user.tier)) {
    return res.status(403).json({ error: 'Alerts are available on Analyst and Desk tiers' });
  }

  try {
    const result = await markAlertRead(req.params.id, req.user.id);
    if (!result) {
      return res.status(404).json({ error: 'Alert not found' });
    }
    return res.json(result);
  } catch (err) {
    console.error('[VYNDR] Alert update error:', err.message);
    return res.status(503).json({ error: 'Alert update failed' });
  }
});

module.exports = router;
