Files
peworkshop/app/api/team-stats/route.js
T
2025-03-16 17:33:55 +00:00

120 lines
3.3 KiB
JavaScript

import { query, queryOne } from "@/lib/db";
import { getToken } from "next-auth/jwt";
export const dynamic = "force-dynamic"; // Disable caching
export async function GET(request) {
try {
// Verify authentication
const token = await getToken({
req: request,
secret:
process.env.NEXTAUTH_SECRET ||
"your-fallback-secret-should-be-at-least-32-chars",
});
if (!token) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
// Check if user has a team
if (!token.teamId) {
return Response.json(
{ error: "You are not part of a team" },
{ status: 404 }
);
}
// Get team information
const team = await queryOne(
"SELECT id, name, code FROM teams WHERE id = ?",
[token.teamId]
);
if (!team) {
return Response.json({ error: "Team not found" }, { status: 404 });
}
// Get total number of clues
const clueCountResult = await queryOne(
"SELECT COUNT(*) as total FROM clues"
);
const totalClues = clueCountResult?.total || 0;
// Get all found clues with timestamps, ordered by found time
const foundClues = await query(
`
SELECT c.id, c.title, tc.found_at
FROM clues c
JOIN team_clues tc ON c.id = tc.clue_id
WHERE tc.team_id = ?
ORDER BY tc.found_at ASC
`,
[token.teamId]
);
// We need to calculate skipped clues - these are clues that have higher IDs than the user's lowest unfound clue
// First, get all clue IDs
const allClueIds = await query("SELECT id FROM clues ORDER BY id ASC");
// Convert to a simple array of IDs
const allClueIdArray = allClueIds.map((c) => c.id);
// Create a set of found clue IDs for easy lookup
const foundClueIdSet = new Set(foundClues.map((c) => c.id));
// Find all unfound clue IDs
const unfoundClueIds = allClueIdArray.filter(
(id) => !foundClueIdSet.has(id)
);
// If there are unfound clues, the ones after the first unfound are "skipped"
let skippedClues = 0;
if (unfoundClueIds.length > 0) {
const lowestUnfoundId = Math.min(...unfoundClueIds);
// Skipped clues are found clues with IDs higher than the lowest unfound
skippedClues = foundClues.filter((c) => c.id > lowestUnfoundId).length;
}
// Get current team rank
const teamRankings = await query(`
SELECT
t.id,
COUNT(DISTINCT tc.clue_id) as cluesFound
FROM
teams t
LEFT JOIN
team_clues tc ON t.id = tc.team_id
GROUP BY
t.id
ORDER BY
cluesFound DESC
`);
// Find current team's position in the ranking
let currentRank = teamRankings.findIndex((t) => t.id === team.id) + 1;
if (currentRank === 0) currentRank = teamRankings.length + 1; // If not found (shouldn't happen)
// Construct response object
const teamStats = {
team,
totalClues,
foundClues,
remainingClues: totalClues - foundClues.length,
skippedClues,
currentRank,
progress:
totalClues > 0 ? Math.round((foundClues.length / totalClues) * 100) : 0,
};
return Response.json(teamStats);
} catch (error) {
console.error("Error fetching team stats:", error);
return Response.json(
{ error: "Failed to fetch team stats: " + error.message },
{ status: 500 }
);
}
}