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

/** POST /api/chat/rooms/[roomId]/leave – Raum verlassen */
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 member = await getMember(roomId, user.id);
  if (!member || member.status !== "active") {
    throw createError({ statusCode: 400, message: "Kein Mitglied" });
  }

  if (member.role === "owner" && !room.isDefault) {
    throw createError({ statusCode: 400, message: "Owner kann den Raum nicht verlassen – lösche ihn stattdessen" });
  }

  await leaveRoom(roomId, user.id);
  return { ok: true };
});
