import { getLeaderboard } from "../../db/scores";
import { getProfile } from "../../db/profile";
import { getUsersMeta } from "../../utils/getUsersMeta";

// GET /api/scores/leaderboard – Top 50 mit Username
export default defineEventHandler(async (event) => {
  const entries = await getLeaderboard(50);
  const userIds = entries.map((e) => e.userId);

  const [profiles, metaMap] = await Promise.all([
    Promise.all(userIds.map((id) => getProfile(id))),
    getUsersMeta(userIds),
  ]);
  const profileMap = new Map(profiles.filter(Boolean).map((p) => [p!.id, p!]));

  return entries.map((row, i) => {
    const p = profileMap.get(row.userId);
    const meta = metaMap[row.userId] ?? { nickname: null, avatar: null };
    return {
      rank: i + 1,
      user_id: row.userId,
      username: p?.username ?? "Anonym",
      avatar: meta.avatar ?? null,
      total_points: row.totalPoints,
      tier: row.tier,
    };
  });
});
