import { Router } from 'express';
import { sendMonthlyReports } from '../jobs/monthlyReport';

const router = Router();

// POST /api/admin/send-monthly-report
// body: { year?: number, month?: number }
// ถ้าไม่ส่ง year/month จะใช้เดือนที่แล้วอัตโนมัติ
router.post('/send-monthly-report', async (req, res) => {
  const now   = new Date();
  const prev  = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const year  = Number(req.body.year  ?? prev.getFullYear());
  const month = Number(req.body.month ?? prev.getMonth() + 1);

  if (month < 1 || month > 12) return res.status(400).json({ error: 'month ต้องอยู่ระหว่าง 1–12' });

  try {
    console.log(`📧 กำลังส่ง monthly report ${year}/${month}...`);
    const result = await sendMonthlyReports(year, month);
    res.json({ ok: true, ...result });
  } catch (e) {
    res.status(500).json({ error: String(e) });
  }
});

export default router;
