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

const UPLOAD_DIR = process.env.UPLOAD_DIR ?? (process.env.NODE_ENV === 'production' ? '/app/uploads' : './uploads')

function getUploadRoot() {
  if (path.isAbsolute(UPLOAD_DIR)) {
    return UPLOAD_DIR
  }
  return path.resolve(process.cwd(), UPLOAD_DIR)
}

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

    // Security: prevent path traversal
    const resolved = path.resolve(filePath)
    const uploadDir = path.resolve(uploadRoot)
    if (!resolved.startsWith(uploadDir + path.sep) && resolved !== 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 })
  }
}
