import { NextRequest, NextResponse } from 'next/server' import { prisma } from '@/lib/db' import { getSession } from '@/lib/auth' import { sendEmail } from '@/lib/email' // POST: Send rapport link via email export async function POST(req: NextRequest, { params }: { params: Promise<{ token: string }> }) { try { const { token } = await params const user = await getSession() if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 }) const { email } = await req.json() if (!email) return NextResponse.json({ error: 'E-Mail-Adresse erforderlich' }, { status: 400 }) const rapport = await (prisma as any).rapport.findUnique({ where: { token }, include: { tenant: { select: { name: true } }, project: { select: { title: true, location: true } }, }, }) if (!rapport) { return NextResponse.json({ error: 'Rapport nicht gefunden' }, { status: 404 }) } const baseUrl = process.env.NEXTAUTH_URL || req.headers.get('origin') || `${req.headers.get('x-forwarded-proto') || 'https'}://${req.headers.get('host')}` || 'http://localhost:3000' const rapportUrl = `${baseUrl}/rapport/${rapport.token}` const pdfUrl = `${baseUrl}/api/rapports/${rapport.token}/pdf` const html = `

Einsatzrapport

${rapport.tenant?.name || ''}

Rapport-Nr.${rapport.reportNumber}
Einsatz${rapport.project?.title || '—'}
Standort${rapport.project?.location || '—'}
Erstellt${new Date(rapport.createdAt).toLocaleString('de-CH')}
Rapport ansehen PDF herunterladen

Dieser Link ist öffentlich zugänglich — keine Anmeldung nötig.
Gesendet von ${user.name || user.email} via app.lageplan.ch

` await sendEmail( email, `Einsatzrapport ${rapport.reportNumber} — ${rapport.project?.title || 'Lageplan'}`, html ) return NextResponse.json({ success: true, message: `Rapport an ${email} gesendet` }) } catch (error) { console.error('Error sending rapport email:', error) return NextResponse.json({ error: 'E-Mail konnte nicht gesendet werden' }, { status: 500 }) } }