import { NextRequest, NextResponse } from 'next/server'
import { readFile } from 'fs/promises'
import path from 'path'

const UPLOAD_DIR = process.env.UPLOAD_DIR ?? './uploads'
// Added comment to force recompile after ENOSPC

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  try {
    const { path: filePathParams } = await params;
    const filePath = path.join(process.cwd(), UPLOAD_DIR, ...filePathParams)

    // Security: prevent path traversal
    const resolved = path.resolve(filePath)
    const uploadDir = path.resolve(path.join(process.cwd(), UPLOAD_DIR))
    if (!resolved.startsWith(uploadDir)) {
      return new NextResponse('Forbidden', { status: 403 })
    }

    const file = await readFile(resolved)
    const ext = path.extname(resolved).toLowerCase()
    const mimeTypes: Record<string, string> = {
      '.pdf': 'application/pdf',
      '.png': 'image/png',
      '.jpg': 'image/jpeg',
      '.jpeg': 'image/jpeg',
      '.gif': 'image/gif',
      '.webp': 'image/webp',
    }

    return new NextResponse(file, {
      headers: {
        'Content-Type': mimeTypes[ext] ?? 'application/octet-stream',
        'Cache-Control': 'public, max-age=86400',
      },
    })
  } catch {
    return new NextResponse('Not Found', { status: 404 })
  }
}
