// src/routes/newsletter.js
const express = require('express');
const db = require('../db');
const rateLimit = require('../middleware/rateLimit');
const requireAdmin = require('../middleware/requireAdmin');

const router = express.Router();

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(email || ''));
}

// PUBLIC — subscribe
router.post('/', rateLimit({ windowMs: 60_000, max: 5 }), (req, res) => {
  const { email } = req.body || {};
  if (!isValidEmail(email)) return res.status(400).json({ error: 'A valid email is required.' });
  try {
    db.prepare('INSERT INTO subscribers (email) VALUES (?)').run(String(email).trim().toLowerCase());
  } catch (err) {
    if (String(err.message || '').includes('UNIQUE')) {
      return res.status(200).json({ ok: true, message: "You're already subscribed — thank you!" });
    }
    return res.status(500).json({ error: 'Could not subscribe right now.' });
  }
  res.status(201).json({ ok: true, message: 'Subscribed! Thank you for following our work.' });
});

// ADMIN — list subscribers
router.get('/', requireAdmin, (req, res) => {
  const rows = db.prepare('SELECT * FROM subscribers ORDER BY created_at DESC').all();
  res.json(rows);
});

// ADMIN — remove a subscriber
router.delete('/:id', requireAdmin, (req, res) => {
  db.prepare('DELETE FROM subscribers WHERE id = ?').run(req.params.id);
  res.json({ ok: true });
});

module.exports = router;
