const mongoose = require("mongoose");
const Report = require("./Report"); 
const ServiceRecord = require("./ServiceRecord"); 

const paymentSchema = new mongoose.Schema({
  paymentCode: String,
  amount: Number,
  date: Date,
  serviceRecordcode: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "ServiceRecord",
    required: true
  }
});


paymentSchema.post("save", async function (doc, next) {
  try {
    const serviceRecord = await ServiceRecord.findById(doc.serviceRecordcode)
      .populate("car")         
      .populate("servicename"); 
    if (!serviceRecord) {
      console.log("No service record found");
      return next();
    }

    await Report.create({
      reportCode: `RPT-${doc.paymentCode}`,
      date: doc.date,
      car: serviceRecord.car,           
      servicename: serviceRecord.servicename, 
      payment: doc._id
    });

    console.log("Report auto-generated ✔️");
    next();
  } catch (error) {
    console.error("Report generation error:", error);
    next(error); 
  }
});

module.exports = mongoose.model("Payment", paymentSchema);