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

/** POST /api/chat/rooms/[roomId]/join – Beitreten oder Anfrage 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 room = await getRoom(roomId);
  if (!room)
    throw createError({ statusCode: 404, message: "Raum nicht gefunden" });

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

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

  if (room.joinMode === "approval") {
    if (existing?.status === "pending") {
      return { status: "already_pending" };
    }
    await joinRoom(roomId, user.id, "pending");
    return { status: "pending" };
  }

  // invite_only
  throw createError({ statusCode: 403, message: "Nur per Einladung" });
});
