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

// Extrahiert aus admin/wishlist/page.tsx — nach Charakter gruppiert
// (Groß-/Kleinschreibung ignoriert), mehrfach gewünschte Charaktere zuerst.
export async function getWishlistGroups() {
  await connectDB();
  const wishes = await CharacterWish.find({}).sort({ createdAt: -1 }).lean();
  const clientIds = [...new Set(wishes.map((w) => String(w.clientId)))];
  const clients = clientIds.length ? await Client.find({ _id: { $in: clientIds } }).select("name").lean() : [];
  const clientNameById = new Map(clients.map((c) => [String(c._id), c.name]));

  const groups = new Map<string, { character: string; entries: typeof wishes }>();
  for (const wish of wishes) {
    const key = wish.character.toLowerCase();
    if (!groups.has(key)) groups.set(key, { character: wish.character, entries: [] });
    groups.get(key)!.entries.push(wish);
  }

  return [...groups.values()]
    .sort((a, b) => b.entries.length - a.entries.length)
    .map((group) => ({
      character: group.character,
      entries: group.entries.map((w) => ({
        id: String(w._id),
        clientName: clientNameById.get(String(w.clientId)) || "?",
        fandom: w.fandom,
        note: w.note,
        createdAt: new Date(w.createdAt).toISOString(),
        status: w.status || "offen",
      })),
    }));
}
