import { queryOne, run } from "@/lib/db"; import { cookies } from "next/headers"; import { verifyToken } from "@/app/api/auth/[...nextauth]/route"; import { nanoid } from "nanoid"; export async function POST(request) { try { const cookieStore = await cookies(); // Check for both possible cookie names const sessionToken = cookieStore.get("next-auth.session-token")?.value || cookieStore.get("__Secure-next-auth.session-token")?.value; if (!sessionToken) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } const userData = verifyToken(sessionToken); if (!userData) { // Add debugging info to help diagnose the issue console.log( "Invalid session token:", sessionToken.substring(0, 10) + "..." ); return Response.json({ error: "Invalid session" }, { status: 401 }); } if (userData.role === "admin") { return Response.json( { error: "Admins cannot create teams" }, { status: 403 } ); } const { name } = await request.json(); if (!name || name.trim() === "") { return Response.json({ error: "Team name is required" }, { status: 400 }); } const teamCode = nanoid(6).toUpperCase(); await run("INSERT INTO teams (name, code) VALUES (?, ?)", [name, teamCode]); const newTeam = await queryOne("SELECT id FROM teams WHERE code = ?", [ teamCode, ]); if (!newTeam || !newTeam.id) { throw new Error("Failed to create team"); } // Update the user's team association in DB await run("UPDATE users SET team_id = ? WHERE id = ?", [ newTeam.id, userData.id, ]); // Include the Set-Cookie header to update the session token with the new teamId const updatedUserData = { ...userData, teamId: newTeam.id, iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60, // 30 days }; const { createToken } = await import("@/app/api/auth/[...nextauth]/route"); const newToken = createToken(updatedUserData); // Calculate expiration date for cookie const expiryDate = new Date(); expiryDate.setDate(expiryDate.getDate() + 30); return new Response( JSON.stringify({ success: true, teamId: newTeam.id, teamName: name }), { status: 201, headers: { "Content-Type": "application/json", "Set-Cookie": `next-auth.session-token=${newToken}; Path=/; HttpOnly; SameSite=Lax; Expires=${expiryDate.toUTCString()}`, }, } ); } catch (error) { console.error("Team creation error:", error); return Response.json( { error: "Failed to create team: " + error.message }, { status: 500 } ); } }