// app/api/users/route.ts import { NextRequest, NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; import type { User, UserGroup } from '@/generated/prisma/client'; type GroupWithUsers = UserGroup & { users: User[] }; // GET bleibt wie gehabt export async function GET() { try { const [groupsRaw, ungrouped] = await Promise.all([ prisma.userGroup.findMany({ orderBy: { name: 'asc' }, include: { users: { orderBy: [{ lastName: 'asc' }, { firstName: 'asc' }], }, }, }), prisma.user.findMany({ where: { groupId: null }, orderBy: [{ lastName: 'asc' }, { firstName: 'asc' }], }), ]); const groups = groupsRaw as GroupWithUsers[]; const allGroups = groups.map((g) => ({ id: g.id, name: g.name })); return NextResponse.json( { groups, ungrouped, allGroups, }, { status: 200 }, ); } catch (err) { console.error('[GET /api/users]', err); return NextResponse.json( { error: 'Interner Serverfehler beim Laden der User.' }, { status: 500 }, ); } } // 🔹 POST: CSV-Import + manuelle Anlage export async function POST(req: NextRequest) { try { const body = (await req.json()) as { nwkennung?: string | null; // aus CSV oder Formular email?: string | null; // optional, falls du später Email mit importierst arbeitsname: string; firstName: string; lastName: string; groupId?: string | null; }; const { nwkennung, email, arbeitsname, firstName, lastName, groupId, } = body; // Pflichtfelder: Name + Arbeitsname if (!nwkennung || !lastName || !firstName || !arbeitsname) { return NextResponse.json( { error: 'nwkennung, lastName, firstName und arbeitsname sind Pflichtfelder.', }, { status: 400 }, ); } const normalizedNwkennung = nwkennung.trim().toLowerCase(); const user = await prisma.user.upsert({ where: { nwkennung: normalizedNwkennung }, update: { lastName, firstName, arbeitsname, groupId: groupId ?? null, }, create: { nwkennung: normalizedNwkennung, lastName, firstName, arbeitsname, groupId: groupId ?? null, }, }); return NextResponse.json( { success: true, user }, { status: 201 }, ); } catch (err) { console.error('[POST /api/users]', err); return NextResponse.json( { error: 'Interner Serverfehler beim CSV-Import.' }, { status: 500 }, ); } }