mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
90 lines
2.3 KiB
JavaScript
90 lines
2.3 KiB
JavaScript
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
|
|
)
|
|
`);
|
|
|
|
// Check if team name already exists
|
|
const existingTeam = await queryOne("SELECT id FROM teams WHERE name = ?", [
|
|
name,
|
|
]);
|
|
if (existingTeam) {
|
|
return Response.json(
|
|
{ error: "Team name already exists" },
|
|
{ status: 409 }
|
|
);
|
|
}
|
|
|
|
// Insert team without created_by field
|
|
const result = await run("INSERT INTO teams (name, code) VALUES (?, ?)", [
|
|
name,
|
|
code,
|
|
]);
|
|
|
|
const teamId = result.lastID;
|
|
if (!teamId) {
|
|
throw new Error("Failed to create team - no ID returned");
|
|
}
|
|
|
|
// Update the user's team_id
|
|
await run("UPDATE users SET team_id = ? WHERE id = ?", [teamId, userId]);
|
|
|
|
// Return a more complete response with all needed data
|
|
return Response.json({
|
|
success: true,
|
|
teamId,
|
|
teamName: name,
|
|
code,
|
|
message: "Team created successfully",
|
|
});
|
|
} catch (error) {
|
|
console.error("Create team error:", error);
|
|
return Response.json(
|
|
{ error: "Failed to create team: " + error.message },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|