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

// Extrahiert aus admin/absences/page.tsx.
export async function getAbsenceList() {
  await connectDB();
  const now = new Date();
  const from = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const [absences, staff] = await Promise.all([
    Absence.find({ endDate: { $gte: from } }).sort({ startDate: 1 }).lean(),
    Client.find({ role: "staff" }).select("name nickname firstName").lean(),
  ]);
  const staffById = new Map(staff.map((s) => [String(s._id), s]));

  return absences.map((a) => ({
    _id: String(a._id),
    clientId: String(a.clientId),
    personName: staffById.get(String(a.clientId))?.nickname || staffById.get(String(a.clientId))?.firstName || staffById.get(String(a.clientId))?.name || "?",
    type: a.type,
    startDate: new Date(a.startDate).toISOString(),
    endDate: new Date(a.endDate).toISOString(),
    note: a.note || "",
  }));
}
