import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getFileStream } from '@/lib/minio'
import { readFile } from 'fs/promises'
import { join } from 'path'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    // ─── 1. Try TenantSymbol first (Phase 1 architecture) ───
    const tenantSymbol = await (prisma as any).tenantSymbol.findUnique({
      where: { id },
      select: { svgPath: true, iconId: true, name: true },
    })

    if (tenantSymbol?.svgPath) {
      // Serve from public/signaturen/ or MinIO
      const contentType = tenantSymbol.svgPath.endsWith('.svg') ? 'image/svg+xml' : 'image/png'
      if (tenantSymbol.svgPath.startsWith('signaturen/')) {
        try {
          const filePath = join(process.cwd(), 'public', tenantSymbol.svgPath)
          const buffer = await readFile(filePath)
          return new NextResponse(buffer, {
            headers: {
              'Content-Type': contentType,
              'Cache-Control': 'public, max-age=31536000',
            },
          })
        } catch {
          console.error('TenantSymbol file not found:', tenantSymbol.svgPath)
        }
      }
      // If not in public/, try MinIO
      try {
        const { stream, contentType: ct } = await getFileStream(tenantSymbol.svgPath)
        const chunks: Buffer[] = []
        for await (const chunk of stream) {
          chunks.push(Buffer.from(chunk))
        }
        const buffer = Buffer.concat(chunks)
        return new NextResponse(buffer, {
          headers: {
            'Content-Type': ct || contentType,
            'Cache-Control': 'public, max-age=86400',
          },
        })
      } catch {
        console.error('Error streaming TenantSymbol from MinIO:', tenantSymbol.svgPath)
      }
    }

    // ─── 2. Fallback: IconAsset (legacy architecture) ───
    const icon = await prisma.iconAsset.findUnique({ where: { id } })

    if (!icon) {
      return NextResponse.json({ error: 'Icon nicht gefunden' }, { status: 404 })
    }

    // Serve system icons from public/signaturen/
    if (icon.isSystem && icon.fileKey.startsWith('signaturen/')) {
      const contentType = icon.mimeType || (icon.fileKey.endsWith('.svg') ? 'image/svg+xml' : 'image/png')
      try {
        const filePath = join(process.cwd(), 'public', icon.fileKey)
        const buffer = await readFile(filePath)
        return new NextResponse(buffer, {
          headers: {
            'Content-Type': contentType,
            'Cache-Control': 'public, max-age=31536000',
          },
        })
      } catch {
        try {
          const altPath = join(process.cwd(), icon.fileKey)
          const buffer = await readFile(altPath)
          return new NextResponse(buffer, {
            headers: {
              'Content-Type': contentType,
              'Cache-Control': 'public, max-age=31536000',
            },
          })
        } catch {
          console.error('System icon file not found:', icon.fileKey)
        }
      }
    }

    // Stream file from MinIO through the app (no external MinIO access needed)
    try {
      const { stream, contentType } = await getFileStream(icon.fileKey)
      const chunks: Buffer[] = []
      for await (const chunk of stream) {
        chunks.push(Buffer.from(chunk))
      }
      const buffer = Buffer.concat(chunks)
      return new NextResponse(buffer, {
        headers: {
          'Content-Type': contentType,
          'Cache-Control': 'public, max-age=86400',
        },
      })
    } catch (streamErr) {
      console.error('Error streaming icon from MinIO:', streamErr)
      return NextResponse.json({ error: 'Icon-Datei nicht gefunden' }, { status: 404 })
    }
  } catch (error) {
    console.error('Error fetching icon:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
