import { NextRequest, NextResponse } from 'next/server'
import { readFile, stat } from 'fs/promises'
import path from 'path'
import { uploadDiskPath } from '@/lib/upload-path'

const ALLOWED_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp'])
const MIME: Record<string, string> = {
  '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
  '.png': 'image/png', '.webp': 'image/webp',
}

export async function GET(
  _req: NextRequest,
  { params }: { params: { path: string[] } }
) {
  const segments = params.path.map((s) => s.replace(/\.\./g, ''))
  const ext = path.extname(segments[segments.length - 1] ?? '').toLowerCase()

  if (!ALLOWED_EXT.has(ext)) {
    return new NextResponse('Not found', { status: 404 })
  }

  const filePath = uploadDiskPath(...segments)

  try {
    await stat(filePath)
    const buf = await readFile(filePath)
    return new NextResponse(buf, {
      headers: {
        'Content-Type': MIME[ext] ?? 'application/octet-stream',
        'Cache-Control': 'public, max-age=31536000, immutable',
      },
    })
  } catch {
    return new NextResponse('Not found', { status: 404 })
  }
}
