import { sendDirectMessage } from "../../db/chat";

/** POST /api/chat/dm – Direktnachricht senden */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);
  const {
    receiverId,
    content,
    replyToId,
    attachmentUrl,
    attachmentType,
    attachmentName,
  } = body as {
    receiverId: string;
    content: string;
    replyToId?: string;
    attachmentUrl?: string;
    attachmentType?: string;
    attachmentName?: string;
  };

  if (!receiverId || (!content?.trim() && !attachmentUrl)) {
    throw createError({
      statusCode: 400,
      message: "receiverId und content/Anhang erforderlich",
    });
  }
  if (receiverId === user.id) {
    throw createError({
      statusCode: 400,
      message: "Nachrichten an sich selbst nicht möglich",
    });
  }
  if ((content ?? "").trim().length > 2000) {
    throw createError({
      statusCode: 400,
      message: "Nachricht zu lang (max. 2000 Zeichen)",
    });
  }

  const data = await sendDirectMessage(
    user.id,
    receiverId,
    (content ?? "").trim(),
    {
      replyToId,
      attachmentUrl,
      attachmentType,
      attachmentName,
    },
  );

  return {
    id: data.id,
    content: data.content,
    createdAt: data.createdAt,
    isOwn: true,
    readAt: null,
    replyTo: data.replyTo,
    attachmentUrl: data.attachmentUrl,
    attachmentType: data.attachmentType,
    attachmentName: data.attachmentName,
    likesCount: data.likesCount,
  };
});
