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

// Serve tenant logo via proxy (no direct MinIO URL needed)
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const tenant = await (prisma as any).tenant.findUnique({
      where: { id: params.id },
      select: { logoFileKey: true, logoUrl: true },
    })

    // Try logoFileKey first, fallback to extracting from logoUrl
    let fileKey = tenant?.logoFileKey
    if (!fileKey && tenant?.logoUrl) {
      const match = tenant.logoUrl.match(/logos\/[^?]+/)
      if (match) fileKey = match[0]
    }

    if (!fileKey) {
      return NextResponse.json({ error: 'Kein Logo vorhanden' }, { status: 404 })
    }

    const { stream, contentType } = await getFileStream(fileKey)

    // 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 logo:', error)
    return NextResponse.json({ error: 'Logo konnte nicht geladen werden' }, { status: 500 })
  }
}
