import { connectDB } from "@/lib/db";
import { GiftVoucher } from "@/models/GiftVoucher";

export async function getVouchers() {
  await connectDB();
  const items = await GiftVoucher.find({}).sort({ createdAt: -1 }).lean();
  const outstandingCount = items.filter((v) => !v.paid && !v.cancelled).length;
  const activeValue = items.filter((v) => v.paid && !v.cancelled && !v.redeemed).reduce((sum, v) => sum + v.amount, 0);
  const redeemedCount = items.filter((v) => v.redeemed).length;

  return {
    vouchers: items.map((item) => ({
      _id: String(item._id),
      code: item.code,
      amount: item.amount,
      purchaserName: item.purchaserName,
      purchaserEmail: item.purchaserEmail,
      recipientName: item.recipientName,
      paid: item.paid,
      cancelled: item.cancelled,
      redeemed: item.redeemed,
      createdAt: new Date(item.createdAt).toISOString(),
    })),
    outstandingCount,
    activeValue,
    redeemedCount,
  };
}
