import { prisma } from "./prisma"; import { Restaurant } from "@/types"; export interface RoomData { users: string[]; restaurants: Restaurant[]; likes: Record; match: string | null; } function generateRoomId(): string { return String(Math.floor(1000 + Math.random() * 9000)); } export async function createRoom(restaurants: Restaurant[]): Promise { const data: RoomData = { users: [], restaurants, likes: {}, match: null, }; let roomId: string; let attempts = 0; while (attempts < 20) { roomId = generateRoomId(); const existing = await prisma.room.findUnique({ where: { id: roomId } }); if (!existing) { await prisma.room.create({ data: { id: roomId, data: JSON.stringify(data) }, }); return roomId; } attempts++; } roomId = generateRoomId() + String(Date.now()).slice(-2); await prisma.room.create({ data: { id: roomId, data: JSON.stringify(data) }, }); return roomId; } export async function getRoomData( roomId: string, ): Promise { const room = await prisma.room.findUnique({ where: { id: roomId } }); if (!room) return null; return JSON.parse(room.data) as RoomData; } export async function updateRoomData( roomId: string, data: RoomData, ): Promise { await prisma.room.update({ where: { id: roomId }, data: { data: JSON.stringify(data) }, }); }