import { getToken } from "next-auth/jwt"; import { query, queryOne, run } from "@/lib/db"; export async function POST(request, context) { 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 }); } const { teamId } = context.params; // Validate that user belongs to this team if (!token.teamId || parseInt(token.teamId, 10) !== parseInt(teamId, 10)) { return Response.json( { error: "You are not a member of this team" }, { status: 403 } ); } // Get current time in ISO format for consistent timing across team members const startTime = new Date().toISOString(); // Store the hunt start time for this team in the database await run(` CREATE TABLE IF NOT EXISTS team_hunt_sessions ( team_id INTEGER PRIMARY KEY, start_time TEXT NOT NULL, initiated_by INTEGER, FOREIGN KEY (team_id) REFERENCES teams(id), FOREIGN KEY (initiated_by) REFERENCES users(id) ) `); // Insert or replace the team's hunt session await run( "INSERT OR REPLACE INTO team_hunt_sessions (team_id, start_time, initiated_by) VALUES (?, ?, ?)", [teamId, startTime, token.id] ); // Update hunt_status and settings tables to activate the hunt 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 record exists const statusExists = await queryOne( "SELECT 1 FROM hunt_status WHERE id = 1" ); if (statusExists) { await run( "UPDATE hunt_status SET is_active = 1, start_time = ? WHERE id = 1", [startTime] ); } else { await run( "INSERT INTO hunt_status (id, is_active, start_time) VALUES (1, 1, ?)", [startTime] ); } // Update settings table await run(` CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL ) `); await run("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", [ "hunt_active", "true", ]); // Get the team members for potential notifications const teamMembers = await query( "SELECT id, username FROM users WHERE team_id = ?", [teamId] ); return Response.json( { success: true, startTime, message: "Hunt started for the entire team", teamMembers: teamMembers.map((m) => m.username), }, { status: 200, headers: { "Cache-Control": "no-store, no-cache, must-revalidate", Pragma: "no-cache", }, } ); } catch (error) { console.error("Start team hunt error:", error); return Response.json( { error: "Failed to start hunt: " + error.message }, { status: 500 } ); } }