Files
peworkshop/app/api/clues/route.js
T

115 lines
3.3 KiB
JavaScript

import { query, queryOne, run } from "@/lib/db";
import { getToken } from "next-auth/jwt";
export const dynamic = "force-dynamic";
export async function GET(request) {
try {
const token = await getToken({
req: request,
secret:
process.env.NEXTAUTH_SECRET ||
"your-fallback-secret-should-be-at-least-32-chars",
});
if (!token) {
console.log("API: Unauthorized request to /api/clues - no token");
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
if (!token.teamId) {
console.log("API: User without team tried to access clues");
return Response.json(
{ error: "You must be part of a team to view clues" },
{ status: 403 }
);
}
try {
await run(`
CREATE TABLE IF NOT EXISTS team_clues (
team_id INTEGER NOT NULL,
clue_id INTEGER NOT NULL,
found_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (team_id, clue_id),
FOREIGN KEY (team_id) REFERENCES teams(id),
FOREIGN KEY (clue_id) REFERENCES clues(id)
)
`);
const tableInfo = await query("PRAGMA table_info(team_clues)");
const hasSkippedColumn = tableInfo.some((col) => col.name === "skipped");
if (!hasSkippedColumn) {
console.log("Adding 'skipped' column to team_clues table");
await run(
"ALTER TABLE team_clues ADD COLUMN skipped BOOLEAN DEFAULT 0"
);
}
} catch (schemaError) {
console.error("Error ensuring database schema:", schemaError);
}
const clues = await query(`
SELECT id, title, description, location
FROM clues
ORDER BY id ASC
`);
const cluesWithStatus = await Promise.all(
clues.map(async (clue) => {
let clueStatus;
try {
clueStatus = await queryOne(
"SELECT found_at, skipped FROM team_clues WHERE team_id = ? AND clue_id = ?",
[token.teamId, clue.id]
);
} catch (error) {
console.error(`Error querying status for clue ${clue.id}:`, error);
clueStatus = await queryOne(
"SELECT found_at FROM team_clues WHERE team_id = ? AND clue_id = ?",
[token.teamId, clue.id]
);
}
return {
...clue,
found: !!clueStatus && !(clueStatus.skipped === 1),
skipped: !!clueStatus && clueStatus.skipped === 1,
available: false,
};
})
);
let firstUnavailableFound = false;
const finalClues = cluesWithStatus.map((clue, index, arr) => {
if (clue.found || clue.skipped) {
return { ...clue, available: true };
}
if (!firstUnavailableFound) {
firstUnavailableFound = true;
return { ...clue, available: true };
}
return { ...clue, available: false };
});
console.log(`API: Returning ${finalClues.length} clues`);
return Response.json(finalClues, {
headers: {
"Cache-Control": "no-store, no-cache, must-revalidate",
Pragma: "no-cache",
Expires: "0",
},
});
} catch (error) {
console.error("Error fetching clues:", error);
return Response.json(
{ error: "Failed to fetch clues: " + error.message },
{ status: 500 }
);
}
}