import { findRoomByInviteCode, getMember, joinRoom } from "../../db/chat-rooms";

/** POST /api/chat/join – Via Invite-Code beitreten */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);
  const code = (body?.code ?? "").trim();

  if (!code) {
    throw createError({ statusCode: 400, message: "Invite-Code erforderlich" });
  }

  const room = await findRoomByInviteCode(code);
  if (!room) {
    throw createError({ statusCode: 404, message: "Ungültiger Invite-Code" });
  }

  const existing = await getMember(room.id, user.id);
  if (existing?.status === "active") {
    return { status: "already_member", roomId: room.id };
  }

  await joinRoom(room.id, user.id, "active");
  return { status: "joined", roomId: room.id };
});
