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

router.get('/stats', auth(), async (req, res, next) => {
  try {
    const db = getDB();
    // Parallel queries — jauh lebih cepat daripada sequential
    const [mR, kR, kpR, sR, dR, rR, pR, uR, bR] = await Promise.all([
      db.query('SELECT COUNT(*) as c FROM materi'),
      db.query('SELECT COUNT(*) as c FROM konsultasi'),
      db.query("SELECT COUNT(*) as c FROM konsultasi WHERE status='pending'"),
      db.query("SELECT COUNT(*) as c FROM newsletter WHERE status='Aktif'"),
      db.query("SELECT COALESCE(SUM(nominal),0) as s FROM donasi WHERE status='Terkonfirmasi'"),
      db.query('SELECT COUNT(*) as c FROM risalah'),
      db.query('SELECT COUNT(*) as c FROM program'),
      db.query('SELECT COUNT(*) as c FROM users'),
      db.query('SELECT COUNT(*) as c FROM berita'),
    ]);
    const stats = {
      materi: mR[0][0].c, konsultasi: kR[0][0].c, konsultasi_pending: kpR[0][0].c,
      subscribers: sR[0][0].c, donasi_total: dR[0][0].s, risalah: rR[0][0].c,
      program: pR[0][0].c, users: uR[0][0].c, berita: bR[0][0].c,
    };
    ok(res, stats);
  } catch (e) { next(e); }
});

module.exports = router;
