import { getMember, createRoomMessage } from "../../../../db/chat-rooms";
import { getUsersMeta } from "../../../../utils/getUsersMeta";

/** POST /api/chat/rooms/[roomId]/messages – Nachricht senden */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const roomId = getRouterParam(event, "roomId");
  if (!roomId) throw createError({ statusCode: 400, message: "roomId fehlt" });

  const member = await getMember(roomId, user.id);
  if (!member || member.status !== "active") {
    throw createError({ statusCode: 403, message: "Kein Mitglied dieses Raums" });
  }

  const body = await readBody(event);
  const content = (body?.content ?? "").trim();
  if (!content && !body?.attachmentUrl) {
    throw createError({ statusCode: 400, message: "Nachricht oder Anhang erforderlich" });
  }
  if (content.length > 2000) {
    throw createError({ statusCode: 400, message: "Nachricht zu lang (max. 2000 Zeichen)" });
  }

  const msg = await createRoomMessage({
    userId: user.id,
    roomId,
    content: content || "",
    replyToId: body?.replyToId,
    attachmentUrl: body?.attachmentUrl,
    attachmentType: body?.attachmentType,
    attachmentName: body?.attachmentName,
  });

  const meta = await getUsersMeta([user.id]);

  return {
    ...msg,
    nickname: meta[user.id]?.nickname ?? "Anonym",
    avatar: meta[user.id]?.avatar ?? null,
    isOwn: true,
  };
});
