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

export async function getMileageTrips() {
  await connectDB();
  const tripDocs = await MileageTrip.find({}).sort({ date: -1 }).lean();
  const trips = tripDocs.map((t) => ({
    _id: String(t._id),
    date: t.date.toISOString(),
    km: t.km,
    ratePerKm: t.ratePerKm,
    amount: t.amount,
    purpose: t.purpose,
  }));
  const yearKey = new Date().getFullYear();
  const tripsThisYear = tripDocs.filter((t) => new Date(t.date).getFullYear() === yearKey);
  const yearTotalKm = tripsThisYear.reduce((sum, t) => sum + t.km, 0);
  const yearTotalAmount = tripsThisYear.reduce((sum, t) => sum + t.amount, 0);
  return { trips, yearTotalKm, yearTotalAmount };
}
