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 } ); } // Update the user's team_id to null await run("UPDATE users SET team_id = NULL WHERE id = ?", [token.id]); // Check if the team is now empty const remainingMembers = await queryOne( "SELECT COUNT(*) as count FROM users WHERE team_id = ?", [teamId] ); // If no more members, delete the team and its associated data if (remainingMembers && remainingMembers.count === 0) { console.log(`Team ${teamId} is now empty, removing it...`); // Delete team's clue progress await run("DELETE FROM team_clues WHERE team_id = ?", [teamId]); // Delete team's hunt session if exists await run("DELETE FROM team_hunt_sessions WHERE team_id = ?", [teamId]); // Finally delete the team itself await run("DELETE FROM teams WHERE id = ?", [teamId]); console.log(`Team ${teamId} has been removed`); } return Response.json({ success: true, message: "You have left the team successfully", }); } catch (error) { console.error("Team leave error:", error); return Response.json( { error: "Failed to leave team: " + error.message }, { status: 500 } ); } }