mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-08 03:50:21 +00:00
50 lines
1.2 KiB
JavaScript
50 lines
1.2 KiB
JavaScript
import { queryOne } from "@/lib/db";
|
|
import { getServerSession } from "next-auth/next";
|
|
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
|
|
|
export async function POST(request) {
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session) {
|
|
return new Response(JSON.stringify({ error: "Unauthorized" }), {
|
|
status: 401,
|
|
});
|
|
}
|
|
|
|
try {
|
|
const { name } = await request.json();
|
|
if (!name) {
|
|
return new Response(JSON.stringify({ error: "Team name is required" }), {
|
|
status: 400,
|
|
});
|
|
}
|
|
|
|
const result = await queryOne(
|
|
"INSERT INTO teams (name, code) VALUES (?, ?)",
|
|
[name, generateTeamCode()]
|
|
);
|
|
|
|
if (!result.insertId) {
|
|
throw new Error("Failed to create team");
|
|
}
|
|
|
|
await queryOne("UPDATE users SET team_id = ? WHERE id = ?", [
|
|
result.insertId,
|
|
session.user.id,
|
|
]);
|
|
|
|
return new Response(JSON.stringify({ teamId: result.insertId }), {
|
|
status: 201,
|
|
});
|
|
} catch (error) {
|
|
console.error("Team creation error:", error);
|
|
return new Response(JSON.stringify({ error: "Failed to create team" }), {
|
|
status: 500,
|
|
});
|
|
}
|
|
}
|
|
|
|
function generateTeamCode() {
|
|
return Math.random().toString(36).substring(2, 8).toUpperCase();
|
|
}
|