mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
59 lines
1.8 KiB
JavaScript
59 lines
1.8 KiB
JavaScript
import { query, 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 Response.json({ success: false, error: 'Unauthorised' }, { status: 401 });
|
|
}
|
|
|
|
// Ensure the user is not an admin
|
|
if (session.user.role === 'admin') {
|
|
return Response.json({ success: false, error: 'Admins cannot create teams' }, { status: 403 });
|
|
}
|
|
|
|
const { name, userId } = await request.json();
|
|
|
|
if (!name || name.trim() === '') {
|
|
return Response.json({ success: false, error: 'Team name is required' });
|
|
}
|
|
|
|
// 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]
|
|
);
|
|
|
|
if (!result || !result.lastID) {
|
|
return Response.json({ success: false, error: 'Failed to create team' });
|
|
}
|
|
|
|
// Update the user's team_id
|
|
await run(
|
|
'UPDATE users SET team_id = ? WHERE id = ?',
|
|
[result.lastID, userId]
|
|
);
|
|
|
|
return Response.json({
|
|
success: true,
|
|
teamId: result.lastID,
|
|
teamCode
|
|
});
|
|
} catch (error) {
|
|
console.error('Create team error:', error);
|
|
return Response.json({
|
|
success: false,
|
|
error: 'Failed to create team: ' + error.message
|
|
});
|
|
}
|
|
} |