import { NextResponse } from 'next/server'
import { checkAgentAuth } from '@/lib/agent-auth'
import { readUploadBytes } from '@/lib/uploads'

export const runtime = 'nodejs'

/**
 * Serves an original handwriting photo to the Mac agent so it can Read it.
 * Bearer-authenticated and separate from the browser-facing /api/image route,
 * which is session-authenticated — the agent has no cookie and a boy has no
 * agent token.
 */
export async function GET(req: Request, { params }: { params: Promise<{ path: string[] }> }) {
  if (!checkAgentAuth(req)) return new NextResponse('Unauthorized', { status: 401 })

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

  return new NextResponse(new Uint8Array(file.buf), {
    headers: { 'Content-Type': file.mediaType, 'Cache-Control': 'no-store' },
  })
}
