import { NextRequest } from 'next/server'
import { auth, getSanitizedHeaders } from '@/lib/auth'
import { prisma } from '@innungsapp/shared'

export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await auth.api.getSession({ headers: await getSanitizedHeaders(req.headers) })
  if (!session?.user) {
    return new Response('Unauthorized', { status: 401 })
  }

  const { id } = await params

  // Verify admin role via UserRole table
  const userRole = await prisma.userRole.findFirst({
    where: { userId: session.user.id, role: 'admin' },
  })
  if (!userRole) {
    return new Response('Forbidden', { status: 403 })
  }

  const termin = await prisma.termin.findUnique({
    where: { id, orgId: userRole.orgId },
    include: { anmeldungen: { include: { member: true } } },
  })

  if (!termin) {
    return new Response('Not found', { status: 404 })
  }

  if (termin.anmeldungen.length === 0) {
    return new Response('Keine Anmeldungen vorhanden', { status: 404 })
  }

  const rows = termin.anmeldungen.map((a) => ({
    Name: a.member.name,
    Email: a.member.email,
    Betrieb: a.member.betrieb ?? '',
    Angemeldet: new Date(a.angemeldetAt).toLocaleDateString('de-DE'),
  }))

  const header = Object.keys(rows[0]).join(';')
  const csv = [header, ...rows.map((r) => Object.values(r).join(';'))].join('\n')

  return new Response('\uFEFF' + csv, {
    headers: {
      'Content-Type': 'text/csv; charset=utf-8',
      'Content-Disposition': `attachment; filename="teilnehmer-${id}.csv"`,
    },
  })
}
