import { readFile } from 'fs/promises'
import path from 'path'
import { NextResponse } from 'next/server'
import { getProjectPublicRoot } from '@/lib/listing-images-upload'

export const dynamic = 'force-dynamic'

/**
 * Serwowanie user-uploadów z `public/uploads/...` bez polegania na symlinku
 * `.next/standalone/public/uploads` (cPanel / Apache często psują ścieżkę).
 * Jeśli Next znajdzie plik w `public` wcześniej, ten handler nie jest wołany.
 */
export async function GET(_req: Request, { params }: { params: { path?: string[] } }) {
  const parts = params.path ?? []
  if (parts.length === 0) {
    return new NextResponse(null, { status: 404 })
  }
  if (parts.some((p) => !p || p.includes('/') || p === '.' || p === '..')) {
    return new NextResponse(null, { status: 400 })
  }
  const uploadsRoot = path.join(getProjectPublicRoot(), 'uploads')
  const filePath = path.join(uploadsRoot, ...parts)
  const resolvedRoot = path.resolve(uploadsRoot)
  const resolvedFile = path.resolve(filePath)
  if (!resolvedFile.startsWith(resolvedRoot + path.sep)) {
    return new NextResponse(null, { status: 400 })
  }
  try {
    const buf = await readFile(resolvedFile)
    const ext = path.extname(resolvedFile).toLowerCase()
    const contentType =
      ext === '.jpg' || ext === '.jpeg'
        ? 'image/jpeg'
        : ext === '.png'
          ? 'image/png'
          : ext === '.webp'
            ? 'image/webp'
            : ext === '.gif'
              ? 'image/gif'
              : 'application/octet-stream'
    return new NextResponse(buf, {
      headers: {
        'Content-Type': contentType,
        'Cache-Control': 'public, max-age=31536000, immutable',
      },
    })
  } catch {
    return new NextResponse(null, { status: 404 })
  }
}
