import { getDmConversations, countUnreadDms } from "../../db/chat";
import { getProfile } from "../../db/profile";
import { getUsersMeta } from "../../utils/getUsersMeta";

/** GET /api/chat/dm-conversations */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);

  const [messages, unreadByPartner] = await Promise.all([
    getDmConversations(user.id),
    countUnreadDms(user.id),
  ]);

  if (messages.length === 0) return [];

  const partnerMap = new Map<string, (typeof messages)[0]>();
  for (const msg of messages) {
    const partnerId = msg.senderId === user.id ? msg.receiverId : msg.senderId;
    if (!partnerMap.has(partnerId)) partnerMap.set(partnerId, msg);
  }

  const partnerIds = Array.from(partnerMap.keys());
  const [profileResults, metaMap] = await Promise.all([
    Promise.all(partnerIds.map((id) => getProfile(id))),
    getUsersMeta(partnerIds),
  ]);
  const profileMap = new Map(
    profileResults.filter(Boolean).map((p) => [p!.id, p!]),
  );

  return Array.from(partnerMap.entries()).map(([partnerId, lastMsg]) => {
    const p = profileMap.get(partnerId);
    const meta = metaMap[partnerId] ?? { nickname: null, avatar: null };
    return {
      partnerId,
      partnerName: meta.nickname ?? p?.username ?? "Anonym",
      partnerAvatar: meta.avatar ?? null,
      lastMessage: lastMsg.content.slice(0, 60),
      lastMessageAt: lastMsg.createdAt,
      isOwn: lastMsg.senderId === user.id,
      unreadCount: unreadByPartner[partnerId] ?? 0,
    };
  });
});
