import { getToken } from "next-auth/jwt"; import { query, queryOne, run } from "@/lib/db"; import { nanoid } from "nanoid"; export async function POST(request) { try { // Get user token from session 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: "Invalid session" }, { status: 401 }); } // Extract user ID from the token const userId = token.id; if (!userId) { return Response.json( { error: "Invalid user information in session" }, { status: 401 } ); } // Parse request body const body = await request.json(); const { name } = body; if (!name || name.trim() === "") { return Response.json({ error: "Team name is required" }, { status: 400 }); } // Generate a unique team code const code = nanoid(6).toUpperCase(); // Create the team - updated schema to match actual database (no created_by column) await run(` CREATE TABLE IF NOT EXISTS teams ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, code TEXT UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) `); // Insert team without created_by field const result = await run("INSERT INTO teams (name, code) VALUES (?, ?)", [ name, code, ]); const teamId = result.lastID; // Update the user's team_id await run("UPDATE users SET team_id = ? WHERE id = ?", [teamId, userId]); return Response.json({ success: true, teamId, code }); } catch (error) { console.error("Create team error:", error); return Response.json( { error: "Failed to create team: " + error.message }, { status: 500 } ); } }