const Invoice = require("../../models/accounts/invoiceModel");
const Payment = require("../../models/accounts/paymentModel");
const { errorResponse } = require("../../utils/errorResponseHandler");

const getInvoiceStatement = async (req, res) => {
  try {
    const { invoiceId } = req.params;
    const orgId = req.user.orgId;

    /* 1️⃣ Fetch invoice */
    const invoice = await Invoice.findOne({
      _id: invoiceId,
      orgId,
      isDeleted: false,
    }).lean();

    if (!invoice) {
      return errorResponse(res, "Invoice not found", 404);
    }

    /* 2️⃣ Fetch related payments */
    const payments = await Payment.find({
      invoiceId,
      orgId,
      isDeleted: false,
    })
      .sort({ paymentDate: 1 })
      .lean();

    /* 3️⃣ Build statement rows */
    const rows = [];
    const openingBalance = 0; // Phase-1
    let balance = openingBalance;

    // Opening
    rows.push({
      date: null,
      type: "Opening",
      reference: "-",
      description: "Opening Balance",
      debit: 0,
      credit: 0,
      balance,
    });

    // Invoice (Debit)
    balance += invoice.grandTotal;
    rows.push({
      date: invoice.generatedDate || invoice.createdAt,
      type: "Invoice",
      reference: invoice.invoiceNumber,
      description: "Invoice Raised",
      debit: invoice.grandTotal,
      credit: 0,
      balance,
      invoiceId: invoice._id, // ✅ REQUIRED FOR VIEW
    });

    // Payments (Credit)
    payments.forEach((p) => {
      balance -= p.amount;
      rows.push({
        date: p.paymentDate,
        type: "Payment",
        reference: p.paymentNumber,
        description: "Payment Received",
        debit: 0,
        credit: p.amount,
        balance,
        paymentId: p._id,
      });
    });

    return res.json({
      success: true,
      data: {
        invoice,
        rows,
        closingBalance: balance,
      },
    });
  } catch (err) {
    return errorResponse(res, "Failed to load statement", 500, err);
  }
};


module.exports = { getInvoiceStatement };
