import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getSession } from '@/lib/auth'
import { getFileStream } from '@/lib/minio'

// Serve plan image (authenticated users only)
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    const project = await (prisma as any).project.findUnique({
      where: { id },
      select: { planImageKey: true },
    })

    if (!project?.planImageKey) {
      return NextResponse.json({ error: 'Kein Plan vorhanden' }, { status: 404 })
    }

    const { stream, contentType } = await getFileStream(project.planImageKey)

    // Collect stream into buffer
    const chunks: Buffer[] = []
    for await (const chunk of stream as AsyncIterable<Buffer>) {
      chunks.push(chunk)
    }
    const buffer = Buffer.concat(chunks)

    return new NextResponse(buffer, {
      headers: {
        'Content-Type': contentType,
        'Cache-Control': 'public, max-age=3600',
      },
    })
  } catch (error) {
    console.error('Error serving plan image:', error)
    return NextResponse.json({ error: 'Fehler beim Laden des Plans' }, { status: 500 })
  }
}
