"use server"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { createRoom, addMember, deleteRoom, removeMember, } from "@/utils/rooms/rooms"; import { UUID_REGEX } from "@/utils/validation"; export type CreateRoomState = { error?: string; } | null; export async function createRoomAction( _prevState: CreateRoomState, formData: FormData, ): Promise { const name = formData.get("name"); if (typeof name !== "string" || !name.trim()) { return { error: "Room name is required." }; } const result = await createRoom(name.trim()); if (result.error) { return { error: "Couldn't create the room." }; } revalidatePath("/rooms"); redirect(`/rooms/${result.roomId}`); } export type AddMemberState = { success?: boolean; error?: string; } | null; export async function addMemberAction( roomId: string, _prevState: AddMemberState, formData: FormData, ): Promise { const userId = formData.get("userId"); if (typeof userId !== "string" || !userId.trim()) { return { error: "User ID is required." }; } const trimmed = userId.trim(); if (!UUID_REGEX.test(trimmed)) { return { error: "Please enter a valid user ID (UUID format)." }; } const result = await addMember(roomId, trimmed); if (result.error) { return { error: "Couldn't add the user to the room or they are already a member.", }; } revalidatePath("/rooms"); return { success: true }; } export async function deleteRoomAction(roomId: string) { const result = await deleteRoom(roomId); if (result.error) { return { error: "Couldn't delete the room." }; } revalidatePath("/rooms"); redirect("/rooms"); } export async function removeMemberAction(roomId: string, userId: string) { const result = await removeMember(roomId, userId); if (result.error) { return { error: "Couldn't remove the member with the id " + userId }; } revalidatePath(`/rooms/${roomId}`); return { success: true }; }