import { getToken } from "next-auth/jwt"; import { query, queryOne, run } from "@/lib/db"; export const dynamic = "force-dynamic"; // Disable caching // Ensure the user is an admin async function verifyAdmin(request) { const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET || "your-fallback-secret-should-be-at-least-32-chars", }); if (!token) { return { authorized: false, error: "Unauthorized", status: 401 }; } if (token.role !== "admin") { return { authorized: false, error: "Admin access required", status: 403 }; } return { authorized: true, token }; } // GET - Fetch all clues for admin export async function GET(request) { try { // Verify admin access const { authorized, error, status, token } = await verifyAdmin(request); if (!authorized) { return Response.json({ error }, { status }); } // Ensure clues table exists with simplified structure (no coordinates) await run(` CREATE TABLE IF NOT EXISTS clues ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, description TEXT NOT NULL, location TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); // Fetch all clues with sequential ordering const clues = await query(` SELECT id, title, description, location, created_at FROM clues ORDER BY id ASC `); console.log(`Admin API: Returning ${clues.length} clues`); return Response.json(clues, { headers: { "Cache-Control": "no-store, no-cache, must-revalidate", Pragma: "no-cache", Expires: "0", }, }); } catch (error) { console.error("Admin clue fetch error:", error); return Response.json( { error: "Failed to fetch clues: " + error.message }, { status: 500 } ); } } // POST - Add a new clue export async function POST(request) { try { // Verify admin access const { authorized, error, status } = await verifyAdmin(request); if (!authorized) { return Response.json({ error }, { status }); } // Parse the request body - simplified without coordinates const { title, description, location = "" } = await request.json(); // Validate required fields if (!title || !description) { return Response.json( { error: "Title and description are required" }, { status: 400 } ); } // Insert the new clue - simplified without coordinates await run( ` INSERT INTO clues (title, description, location) VALUES (?, ?, ?) `, [title, description, location] ); // Get the inserted clue ID const newClue = await queryOne("SELECT last_insert_rowid() as id"); return Response.json( { success: true, message: "Clue added successfully", clueId: newClue.id, }, { status: 201 } ); } catch (error) { console.error("Admin clue creation error:", error); return Response.json( { error: "Failed to add clue: " + error.message }, { status: 500 } ); } }