101 lines
2.7 KiB
JavaScript
101 lines
2.7 KiB
JavaScript
const express = require('express');
|
|
const db = require('../database');
|
|
|
|
const router = express.Router();
|
|
|
|
// Pick a random game with filters and repeat avoidance
|
|
router.post('/pick', (req, res) => {
|
|
try {
|
|
const {
|
|
playerCount,
|
|
drawing,
|
|
length,
|
|
familyFriendly,
|
|
sessionId
|
|
} = req.body;
|
|
|
|
// Build query for eligible games
|
|
let query = 'SELECT * FROM games WHERE enabled = 1';
|
|
const params = [];
|
|
|
|
if (playerCount) {
|
|
const count = parseInt(playerCount);
|
|
query += ' AND min_players <= ? AND max_players >= ?';
|
|
params.push(count, count);
|
|
}
|
|
|
|
if (drawing === 'only') {
|
|
query += ' AND game_type = ?';
|
|
params.push('Drawing');
|
|
} else if (drawing === 'exclude') {
|
|
query += ' AND (game_type != ? OR game_type IS NULL)';
|
|
params.push('Drawing');
|
|
}
|
|
|
|
if (length) {
|
|
if (length === 'short') {
|
|
query += ' AND (length_minutes <= 15 OR length_minutes IS NULL)';
|
|
} else if (length === 'medium') {
|
|
query += ' AND length_minutes > 15 AND length_minutes <= 25';
|
|
} else if (length === 'long') {
|
|
query += ' AND length_minutes > 25';
|
|
}
|
|
}
|
|
|
|
if (familyFriendly !== undefined) {
|
|
query += ' AND family_friendly = ?';
|
|
params.push(familyFriendly ? 1 : 0);
|
|
}
|
|
|
|
// Get eligible games
|
|
const stmt = db.prepare(query);
|
|
let eligibleGames = stmt.all(...params);
|
|
|
|
if (eligibleGames.length === 0) {
|
|
return res.status(404).json({
|
|
error: 'No games match the current filters',
|
|
suggestion: 'Try adjusting your filters or enabling more games'
|
|
});
|
|
}
|
|
|
|
// Apply repeat avoidance if session provided
|
|
if (sessionId) {
|
|
const lastGames = db.prepare(`
|
|
SELECT game_id FROM session_games
|
|
WHERE session_id = ?
|
|
ORDER BY played_at DESC
|
|
LIMIT 2
|
|
`).all(sessionId);
|
|
|
|
const excludeIds = lastGames.map(g => g.game_id);
|
|
|
|
if (excludeIds.length > 0) {
|
|
eligibleGames = eligibleGames.filter(game => !excludeIds.includes(game.id));
|
|
}
|
|
|
|
if (eligibleGames.length === 0) {
|
|
return res.status(404).json({
|
|
error: 'All eligible games have been played recently',
|
|
suggestion: 'Enable more games or adjust your filters',
|
|
recentlyPlayed: excludeIds
|
|
});
|
|
}
|
|
}
|
|
|
|
// Pick random game from eligible pool
|
|
const randomIndex = Math.floor(Math.random() * eligibleGames.length);
|
|
const selectedGame = eligibleGames[randomIndex];
|
|
|
|
res.json({
|
|
game: selectedGame,
|
|
poolSize: eligibleGames.length,
|
|
totalEnabled: eligibleGames.length + (sessionId ? 2 : 0) // Approximate
|
|
});
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|
|
|