const router = require('express').Router();
const Payment = require('../models/Payment');
const Invoice = require('../models/Invoice');
const { auth } = require('../middleware/auth');

router.get('/', auth, async (req, res) => {
  try {
    const payments = await Payment.find().sort({ createdAt: -1 }).populate({ path: 'invoice_id', populate: { path: 'customer_id', select: 'name' } });
    res.json(payments);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.post('/', auth, async (req, res) => {
  try {
    const p = await Payment.create(req.body);
    const inv = await Invoice.findById(req.body.invoice_id);
    const allPayments = await Payment.find({ invoice_id: req.body.invoice_id, status: 'confirmed' });
    const totalPaid = allPayments.reduce((sum, x) => sum + x.amount, 0);
    if (inv && totalPaid >= inv.total_amount) {
      await Invoice.findByIdAndUpdate(req.body.invoice_id, { status: 'paid' });
    }
    res.status(201).json(p);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.delete('/:id', auth, async (req, res) => {
  try {
    await Payment.findByIdAndDelete(req.params.id);
    res.json({ message: 'Deleted successfully' });
  } catch (err) { res.status(500).json({ message: err.message }); }
});

module.exports = router;
