const Payment = require("../model/Payment");
const generateSequence = require("../utils/generateSequence");

const createPayment = async (req, res) => {
  try {
    const userId = req.session?.user?.id;
    const paymentNumber = await generateSequence("payment", "PAY");
    const payment = await Payment.create({ ...req.body, userId, paymentNumber });
    const populated = await payment.populate({
      path: "serviceRecord",
      populate: [{ path: "car" }, { path: "service" }],
    });
    return res.status(201).json(populated);
  } catch (error) {
    return res.status(400).json({ message: error.message });
  }
};

const getPayments = async (req, res) => {
  const userId = req.session?.user?.id;
  const payments = await Payment.find({ userId })
    .populate({
      path: "serviceRecord",
      populate: [{ path: "car" }, { path: "service" }],
    })
    .sort({ paymentDate: -1 });
  return res.json(payments);
};

const getBillByPaymentId = async (req, res) => {
  const userId = req.session?.user?.id;
  const payment = await Payment.findOne({ _id: req.params.id, userId }).populate({
    path: "serviceRecord",
    populate: [{ path: "car" }, { path: "service" }],
  });
  if (!payment) return res.status(404).json({ message: "Payment not found" });

  return res.json({
    billNumber: `BILL-${payment.paymentNumber}`,
    receiver: payment.receiverName,
    paymentDate: payment.paymentDate,
    amountPaid: payment.amountPaid,
    recordNumber: payment.serviceRecord.recordNumber,
    plateNumber: payment.serviceRecord.car.plateNumber,
    carModel: payment.serviceRecord.car.model,
    serviceName: payment.serviceRecord.service.serviceName,
    servicePrice: payment.serviceRecord.service.servicePrice,
  });
};

const getDailyReport = async (req, res) => {
  const userId = req.session?.user?.id;
  const { date } = req.query;
  if (!date) return res.status(400).json({ message: "date query is required" });

  const dayStart = new Date(`${date}T00:00:00.000Z`);
  const dayEnd = new Date(`${date}T23:59:59.999Z`);

  const payments = await Payment.find({
    userId,
    paymentDate: { $gte: dayStart, $lte: dayEnd },
  }).populate({
    path: "serviceRecord",
    populate: [{ path: "car" }, { path: "service" }],
  });

  const rows = payments.map((payment) => ({
    plateNumber: payment.serviceRecord.car.plateNumber,
    serviceName: payment.serviceRecord.service.serviceName,
    amountPaid: payment.amountPaid,
    paymentDate: payment.paymentDate,
  }));

  const totalAmountPaid = rows.reduce((sum, row) => sum + row.amountPaid, 0);
  return res.json({ date, totalAmountPaid, rows });
};

module.exports = { createPayment, getPayments, getBillByPaymentId, getDailyReport };

