96 lines
3.0 KiB
TypeScript
96 lines
3.0 KiB
TypeScript
// /api/team/create/route.ts
|
|
import { NextResponse, type NextRequest } from 'next/server'
|
|
import { prisma } from '@/app/lib/prisma'
|
|
import { sendServerSSEMessage } from '@/app/lib/sse-server-client'
|
|
|
|
export const dynamic = 'force-dynamic'
|
|
|
|
export async function POST(req: NextRequest) {
|
|
try {
|
|
const { teamname, leader }: { teamname?: string; leader?: string } = await req.json()
|
|
if (!teamname?.trim()) {
|
|
return NextResponse.json({ message: 'Teamname fehlt.' }, { status: 400 })
|
|
}
|
|
|
|
const dup = await prisma.team.findFirst({ where: { name: teamname } })
|
|
if (dup) {
|
|
return NextResponse.json({ message: 'Teamname bereits vergeben.' }, { status: 400 })
|
|
}
|
|
|
|
const newTeam = await prisma.team.create({
|
|
data: {
|
|
name: teamname,
|
|
leaderId: leader ?? null,
|
|
activePlayers: leader ? [leader] : [],
|
|
inactivePlayers: [],
|
|
},
|
|
})
|
|
|
|
if (leader) {
|
|
const user = await prisma.user.findUnique({ where: { steamId: leader } })
|
|
if (!user) {
|
|
await prisma.team.delete({ where: { id: newTeam.id } })
|
|
return NextResponse.json({ message: 'Leader-Benutzer nicht gefunden.' }, { status: 404 })
|
|
}
|
|
|
|
// user dem Team zuordnen
|
|
await prisma.user.update({
|
|
where: { steamId: leader },
|
|
data: { teamId: newTeam.id },
|
|
})
|
|
|
|
// 🔔 (optional) persistente Notification
|
|
const note = await prisma.notification.create({
|
|
data: {
|
|
steamId: leader,
|
|
title: 'Team erstellt',
|
|
message: `Du hast erfolgreich das Team „${teamname}“ erstellt.`,
|
|
actionType: 'team-created',
|
|
actionData: newTeam.id,
|
|
},
|
|
})
|
|
|
|
// ➜ Sofort an Notification-Center
|
|
await sendServerSSEMessage({
|
|
type: 'notification',
|
|
targetUserIds: [leader],
|
|
message: note.message,
|
|
id: note.id,
|
|
actionType: note.actionType ?? undefined,
|
|
actionData: note.actionData ?? undefined,
|
|
createdAt: note.createdAt.toISOString(),
|
|
})
|
|
|
|
// ✅ ➜ HIER: Self-Refresh für den Ersteller
|
|
await sendServerSSEMessage({
|
|
type: 'self-updated', // <— stelle sicher, dass dein Client darauf hört
|
|
targetUserIds: [leader],
|
|
})
|
|
}
|
|
|
|
// (Optional) Broadcasts
|
|
await sendServerSSEMessage({
|
|
type: 'team-created',
|
|
title: 'Team erstellt',
|
|
message: `Das Team „${teamname}“ wurde erstellt.`,
|
|
teamId: newTeam.id,
|
|
})
|
|
|
|
await sendServerSSEMessage({
|
|
type: 'team-updated',
|
|
teamId: newTeam.id,
|
|
})
|
|
|
|
return NextResponse.json(
|
|
{ message: 'Team erstellt', team: newTeam },
|
|
{ headers: { 'Cache-Control': 'no-store' } },
|
|
)
|
|
} catch (error: any) {
|
|
if (error?.code === 'P2002') {
|
|
return NextResponse.json({ message: 'Teamname bereits vergeben.' }, { status: 400 })
|
|
}
|
|
console.error('❌ Fehler beim Team erstellen:', error)
|
|
return NextResponse.json({ message: 'Interner Serverfehler.' }, { status: 500 })
|
|
}
|
|
}
|