import { createRoom } from "../../../db/chat-rooms";
import { getProfile } from "../../../db/profile";

/** POST /api/chat/rooms – Room erstellen (legend only) */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);

  // Legend-Check
  const profile = await getProfile(user.id);
  if (profile?.plan !== "legend") {
    throw createError({
      statusCode: 403,
      message: "Nur Legend-Mitglieder können Gruppen erstellen",
    });
  }

  const body = await readBody(event);
  const name = (body?.name ?? "").trim();
  if (!name || name.length > 60) {
    throw createError({
      statusCode: 400,
      message: "Name erforderlich (max. 60 Zeichen)",
    });
  }

  const description = (body?.description ?? "").trim().slice(0, 200) || null;
  const isPublic = body?.isPublic === true;
  const joinMode = isPublic
    ? "open"
    : body?.joinMode === "approval"
      ? "approval"
      : "invite_only";

  const room = await createRoom({
    name,
    description: description ?? undefined,
    isPublic,
    joinMode,
    createdBy: user.id,
    avatarUrl:
      typeof body?.avatarUrl === "string"
        ? body.avatarUrl.trim() || undefined
        : undefined,
  });

  return room;
});
