import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { readUpload, contentTypeFor } from '@/lib/images'

// Authenticated file server. The proxy middleware can't gate file paths
// because middleware doesn't run on /_next/image-style requests and we
// want auth on each photo fetch.
export async function GET(
  _req: Request,
  { params }: { params: Promise<{ path: string[] }> },
) {
  const session = await getSession()
  if (!session) {
    return new NextResponse('Unauthorized', { status: 401 })
  }

  const { path } = await params
  const rel = path.join('/')
  const buf = await readUpload(rel)
  if (!buf) return new NextResponse('Not found', { status: 404 })

  return new NextResponse(new Uint8Array(buf), {
    status: 200,
    headers: {
      'content-type': contentTypeFor(rel),
      'cache-control': 'private, max-age=86400',
    },
  })
}
