import { query, queryOne } from "@/lib/db"; import { getToken } from "next-auth/jwt"; export const dynamic = "force-dynamic"; // Disable caching export async function POST(request) { try { 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 must be part of a team to mark clues as found" }, { status: 403 } ); } // Parse request body const { clueId } = await request.json(); // Validate clueId is a number if (isNaN(parseInt(clueId))) { return Response.json({ error: "Invalid clue ID" }, { status: 400 }); } // Check if clue exists const clue = await queryOne("SELECT id FROM clues WHERE id = ?", [clueId]); if (!clue) { return Response.json({ error: "Clue not found" }, { status: 404 }); } // Check if clue was already found const alreadyFound = await queryOne( "SELECT * FROM team_clues WHERE team_id = ? AND clue_id = ?", [token.teamId, clueId] ); if (alreadyFound) { return Response.json({ success: true, message: "This clue was already marked as found", alreadyFound: true, }); } // Create team_clues table if it doesn't exist await queryOne(` 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) ) `); // Record that the team found this clue await queryOne("INSERT INTO team_clues (team_id, clue_id) VALUES (?, ?)", [ token.teamId, clueId, ]); console.log(`Clue ${clueId} marked as found for team ${token.teamId}`); // Return successful response return Response.json({ success: true, message: "Clue marked as found successfully", }); } catch (error) { console.error("Error marking clue as found:", error); return Response.json( { error: "Failed to mark clue as found: " + error.message }, { status: 500 } ); } }