// app/api/devices/[id]/history/route.ts import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; type RouteParams = { id: string }; type RouteContext = { params: Promise }; export async function GET(_req: Request, ctx: RouteContext) { const { id } = await ctx.params; if (!id) { return NextResponse.json({ error: 'MISSING_ID' }, { status: 400 }); } try { const history = await prisma.deviceHistory.findMany({ where: { deviceId: id }, orderBy: { changedAt: 'desc' }, include: { changedBy: true, // ๐Ÿ‘ˆ User-Relation laden }, }); const result = history.map((entry) => { const user = entry.changedBy; // ๐Ÿ‘‡ Anzeigename nach deiner neuen Logik: // arbeitsname > "Vorname Nachname" > nwkennung > email const changedByName = user?.arbeitsname ?? (user?.firstName && user?.lastName ? `${user.firstName} ${user.lastName}` : user?.nwkennung ?? user?.email ?? null); // snapshot.changes aus dem JSON holen (bei CREATED evtl. leer) let changes: { field: string; from: string | null; to: string | null; }[] = []; const snapshot = entry.snapshot as any; if (snapshot && Array.isArray(snapshot.changes)) { changes = snapshot.changes.map((c: any) => ({ field: String(c.field), from: c.before ?? null, to: c.after ?? null, })); } return { id: entry.id, changeType: entry.changeType, changedAt: entry.changedAt.toISOString(), changedBy: changedByName, // ๐Ÿ‘ˆ jetzt schรถn formatiert changes, }; }); return NextResponse.json(result); } catch (err) { console.error('[GET /api/devices/[id]/history]', err); return NextResponse.json( { error: 'INTERNAL_ERROR' }, { status: 500 }, ); } }