import { getDmHistory, markDmsAsRead } from "../../../db/chat";
import { getProfile } from "../../../db/profile";

/** GET /api/chat/dm/[userId]?page=1 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const partnerId = getRouterParam(event, "userId");
  if (!partnerId)
    throw createError({ statusCode: 400, message: "userId fehlt" });

  const page = Math.max(1, parseInt((getQuery(event).page as string) || "1"));

  const [messages, partnerProfile] = await Promise.all([
    getDmHistory(user.id, partnerId, page),
    getProfile(partnerId),
    markDmsAsRead(partnerId, user.id),
  ]);

  return {
    partner: partnerProfile
      ? {
          id: partnerProfile.id,
          nickname: partnerProfile.nickname ?? partnerProfile.username ?? "Anonym",
          username: partnerProfile.username ?? "anonym",
          avatar: partnerProfile.avatar,
        }
      : { id: partnerId, nickname: "Anonym", username: "anonym", avatar: null },
    messages: [...messages].reverse().map((m) => ({
      id: m.id,
      senderId: m.senderId,
      receiverId: m.receiverId,
      content: m.content,
      createdAt: m.createdAt,
      isOwn: m.senderId === user.id,
      readAt: m.readAt,
      attachmentUrl: m.attachmentUrl,
      attachmentType: m.attachmentType,
      attachmentName: m.attachmentName,
      likesCount: m.likesCount,
      replyTo: m.replyTo
        ? {
            id: m.replyTo.id,
            senderId: m.replyTo.senderId,
            content: m.replyTo.content,
          }
        : null,
    })),
  };
});
