import { query, queryOne, run } from "@/lib/db"; // Add 'run' to the import 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, skipped = false } = 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 or skipped const alreadyProcessed = await queryOne( "SELECT * FROM team_clues WHERE team_id = ? AND clue_id = ?", [token.teamId, clueId] ); if (alreadyProcessed) { // If skipping is requested, update the record regardless of previous state if (skipped) { await run( "UPDATE team_clues SET skipped = 1 WHERE team_id = ? AND clue_id = ?", [token.teamId, clueId] ); return Response.json({ success: true, message: "Clue marked as skipped", skipped: true, }); } // For non-skip requests on already processed clues return Response.json({ success: true, message: "This clue was already processed", alreadyFound: !(alreadyProcessed.skipped === 1), alreadySkipped: alreadyProcessed.skipped === 1, }); } // Ensure the team_clues table has a skipped column 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, skipped BOOLEAN DEFAULT 0, PRIMARY KEY (team_id, clue_id), FOREIGN KEY (team_id) REFERENCES teams(id), FOREIGN KEY (clue_id) REFERENCES clues(id) ) `); // Add column if it doesn't exist (safe operation) try { await run("ALTER TABLE team_clues ADD COLUMN skipped BOOLEAN DEFAULT 0"); } catch (e) { // Column likely already exists, continue } // Record that the team found or skipped this clue await run( "INSERT INTO team_clues (team_id, clue_id, skipped) VALUES (?, ?, ?)", [token.teamId, clueId, skipped ? 1 : 0] ); return Response.json({ success: true, message: skipped ? "Clue skipped successfully" : "Clue marked as found", skipped: skipped, }); } catch (error) { console.error("Error marking clue:", error); return Response.json( { error: "Failed to process clue: " + error.message }, { status: 500 } ); } }