const express = require("express");
const router = express.Router();
const Payment = require("../models/Payment");
const Report = require('../models/Report'); 


router.post("/add", async (req, res) => {
  try {
    const payment = new Payment(req.body);
    const saved = await payment.save();

    res.status(201).json({
      message: "Payment saved successfully (Report auto-generated)",
      payment: saved
    });
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});


router.get("/all", async (req, res) => {
  try {
    const payments = await Payment.find().populate("serviceRecordcode");
    res.json(payments);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

router.put("/update/:id", async (req, res) => {
  try {
    const payment = await Payment.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    );

    res.json(payment);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

router.delete("/delete/:id", async (req, res) => {
  try {
    const payment = await Payment.findByIdAndDelete(req.params.id);
    res.json(payment);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

module.exports = router;