mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
71 lines
1.9 KiB
JavaScript
71 lines
1.9 KiB
JavaScript
import { queryOne, run } from "../../../../lib/db";
|
|
import { getServerSession } from "next-auth/next";
|
|
import { authOptions } from "../../auth/[...nextauth]/route";
|
|
import { nanoid } from "nanoid";
|
|
|
|
export async function POST(request) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
|
|
// Debugging: Log the session
|
|
console.log("Session:", session);
|
|
|
|
if (!session) {
|
|
return new Response(
|
|
JSON.stringify({ success: false, error: "Unauthorised" }),
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
// Ensure the user is not an admin
|
|
if (session.user.role === "admin") {
|
|
return new Response(
|
|
JSON.stringify({ success: false, error: "Admins cannot create teams" }),
|
|
{ status: 403 }
|
|
);
|
|
}
|
|
|
|
const { name, userId } = await request.json();
|
|
|
|
if (!name || name.trim() === "") {
|
|
return new Response(
|
|
JSON.stringify({ success: false, error: "Team name is required" }),
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Generate a unique team code (6 characters)
|
|
const teamCode = nanoid(6).toUpperCase();
|
|
|
|
// Insert the new team
|
|
const result = await run("INSERT INTO teams (name, code) VALUES (?, ?)", [
|
|
name,
|
|
teamCode,
|
|
]);
|
|
|
|
// Fetch the newly created team ID
|
|
const newTeam = await queryOne("SELECT id FROM teams WHERE code = ?", [
|
|
teamCode,
|
|
]);
|
|
|
|
// Update the user's team_id
|
|
await run("UPDATE users SET team_id = ? WHERE id = ?", [
|
|
newTeam.id,
|
|
userId,
|
|
]);
|
|
|
|
// Update the session with the new teamId
|
|
session.user.teamId = newTeam.id;
|
|
|
|
return new Response(JSON.stringify({ success: true, teamId: newTeam.id }), {
|
|
status: 201,
|
|
});
|
|
} catch (error) {
|
|
console.error("Team creation error:", error);
|
|
return new Response(
|
|
JSON.stringify({ success: false, error: "Failed to create team" }),
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|