// File d'attente de questions par room. Préchargée au lancement de la partie // depuis la DB (si dispo), sinon depuis la banque en dur. Le QuizRound y pioche. import { hasDb } from "../../../db" import { loadQuizPool } from "../../../db/quiz-repo" import type { ServerRoom } from "../../../rooms" import { QUIZ_QUESTIONS, type QuizQuestion } from "./questions" interface RoomPool { queue: QuizQuestion[] /** true si les questions viennent de la DB (→ marquer jouées). */ fromDb: boolean } const poolByRoom = new WeakMap() function shuffle(items: T[]): T[] { const arr = [...items] for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)) ;[arr[i], arr[j]] = [arr[j], arr[i]] } return arr } /** Précharge les questions de la partie. À appeler avant de lancer le moteur. */ export async function prepareQuizForRoom(room: ServerRoom): Promise { const needed = room.settings.rounds.filter((r) => r.type === "quiz").length let queue: QuizQuestion[] = [] let fromDb = false if (hasDb) { try { queue = await loadQuizPool(room.code, Math.max(needed, 1)) fromDb = queue.length > 0 } catch (err) { console.error("[quiz] chargement DB échoué, fallback banque en dur", err) } } if (queue.length === 0) { queue = shuffle(QUIZ_QUESTIONS) fromDb = false } poolByRoom.set(room, { queue, fromDb }) } /** Pioche la prochaine question. Fallback aléatoire si la file est vide. */ export function takeQuestion(room: ServerRoom): { question: QuizQuestion fromDb: boolean } { const pool = poolByRoom.get(room) if (pool && pool.queue.length > 0) { return { question: pool.queue.shift()!, fromDb: pool.fromDb } } const question = QUIZ_QUESTIONS[Math.floor(Math.random() * QUIZ_QUESTIONS.length)] return { question, fromDb: false } }