import { Request, Response } from "express";
import { isValidObjectId } from "mongoose";
import order from "../../models/order";

const getAllOrders = async (req: Request, res: Response) => {
  const { page = 1, perPage = 10, dispatched } = req.query;

  try {
    const filter: Record<string, any> = {};
    if (dispatched === "true") filter.amountDispatched = true;
    else if (dispatched === "false") filter.amountDispatched = { $ne: true };

    const [orders, totalItemCount, statsAgg] = await Promise.all([
      order
        .find(filter)
        .sort({ createdAt: -1 })
        .skip((Number(page) - 1) * Number(perPage))
        .limit(Number(perPage)),
      order.countDocuments(filter),
      // Payment summary cards (admin/payments) need totals across every
      // order regardless of the current dispatched filter/page - computed
      // here instead of the UI fetching the whole collection to sum client-side.
      order.aggregate([
        {
          $project: {
            amountDispatched: 1,
            net: {
              $add: [
                { $multiply: [{ $ifNull: ["$subtotal", 0] }, 0.92] },
                { $ifNull: ["$shippingAmount", 0] },
                { $ifNull: ["$taxAmount", 0] },
              ],
            },
          },
        },
        {
          $group: {
            _id: null,
            totalPayments: { $sum: "$net" },
            dispatchedPayments: {
              $sum: { $cond: ["$amountDispatched", "$net", 0] },
            },
            pendingPayments: {
              $sum: { $cond: ["$amountDispatched", 0, "$net"] },
            },
            processedCount: {
              $sum: { $cond: ["$amountDispatched", 1, 0] },
            },
          },
        },
      ]),
    ]);

    const s = statsAgg[0] || {
      totalPayments: 0,
      dispatchedPayments: 0,
      pendingPayments: 0,
      processedCount: 0,
    };
    const stats = {
      totalPayments: s.totalPayments,
      dispatchedPayments: s.dispatchedPayments,
      pendingPayments: s.pendingPayments,
      processedCount: s.processedCount,
    };

    res.status(200).json({ orders, totalItemCount, stats });
  } catch (err) {
    res.status(500).json({ message: err });
  }
};

export { getAllOrders };
