import { getServerSession } from "next-auth/next"; import { authOptions, verifyToken } from "../../auth/[...nextauth]/route"; import { query, queryOne, run } from "../../../../lib/db"; import { cookies } from "next/headers"; export const dynamic = "force-dynamic"; // Disable caching // Helper function to ensure the hunt_status table exists async function ensureHuntStatusTableExists() { try { // Create hunt_status table if it doesn't exist await run(` CREATE TABLE IF NOT EXISTS hunt_status ( id INTEGER PRIMARY KEY CHECK (id = 1), is_active BOOLEAN DEFAULT 0, start_time TEXT, end_time TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); // Check if we need to insert the initial record const status = await queryOne("SELECT * FROM hunt_status LIMIT 1"); if (!status) { await run( "INSERT INTO hunt_status (id, is_active, start_time) VALUES (1, 0, NULL)" ); } return true; } catch (error) { console.error("Error ensuring hunt_status table:", error); return false; } } // Fallback function to get user data when session fails async function getUserFromToken() { try { const cookieStore = await cookies(); const sessionToken = cookieStore.get("next-auth.session-token")?.value; if (!sessionToken) return null; const userData = verifyToken(sessionToken); if (!userData) return null; // Verify that the user exists and get their role const user = await queryOne("SELECT id, role FROM users WHERE id = ?", [ userData.id || userData.sub, ]); return user; } catch (error) { console.error("Error getting user from token:", error); return null; } } export async function POST(request) { try { // First ensure the table exists await ensureHuntStatusTableExists(); // Try to get session, with fallback to token-based auth let user = null; let session = null; try { session = await getServerSession(authOptions); user = session?.user; } catch (sessionError) { console.warn( "Session error, trying fallback auth:", sessionError.message ); user = await getUserFromToken(); } // Verify the user is authenticated if (!user) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } // Check if user is admin if (user.role !== "admin") { return Response.json( { error: "Only admins can start the hunt" }, { status: 403 } ); } // Check if hunt is already in progress const huntStatus = await queryOne("SELECT * FROM hunt_status LIMIT 1"); if (huntStatus && huntStatus.is_active) { return Response.json( { error: "Hunt is already in progress" }, { status: 400 } ); } // Start the hunt by updating the status const now = new Date().toISOString(); // Update the hunt_status table await run( `UPDATE hunt_status SET is_active = ?, start_time = ? WHERE id = 1`, [true, now] ); // Also update settings table for compatibility try { await run("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", [ "hunt_active", "true", ]); } catch (err) { console.log( "Could not update settings table (might not exist yet):", err.message ); } return Response.json( { success: true, message: "Hunt started successfully", startTime: now }, { status: 200 } ); } catch (error) { console.error("Start hunt error:", error); return Response.json({ error: "Failed to start hunt" }, { status: 500 }); } }