const express = require('express');
const router = express.Router();
const { getDB } = require('../config/database');
const { auth } = require('../middleware/auth');
const { ok, err } = require('../helpers/response');

router.get('/', auth(), async (req, res, next) => {
  try {
    const db = getDB();
    const [data] = await db.query('SELECT * FROM newsletter ORDER BY created_at DESC');
    const stats = {
      total: data.length,
      aktif: data.filter(n => n.status === 'Aktif').length,
      nonaktif: data.filter(n => n.status !== 'Aktif').length,
    };
    ok(res, { data, stats });
  } catch (e) { next(e); }
});

router.post('/', async (req, res, next) => {
  try {
    const db = getDB();
    const { email } = req.body;
    if (!email || !/\S+@\S+\.\S+/.test(email)) return err(res, 'Email tidak valid');
    try {
      await db.query('INSERT INTO newsletter (email) VALUES (?)', [email]);
      ok(res, null, 'Berhasil berlangganan');
    } catch {
      err(res, 'Email sudah terdaftar');
    }
  } catch (e) { next(e); }
});

router.delete('/:id', auth(['Admin']), async (req, res, next) => {
  try {
    const db = getDB();
    await db.query('DELETE FROM newsletter WHERE id = ?', [req.params.id]);
    ok(res, null, 'Subscriber dihapus');
  } catch (e) { next(e); }
});

module.exports = router;
