import { NextResponse } from 'next/server'
import { readFile } from 'fs/promises'
import { db } from '@/lib/db'
import { absFromStored } from '@/lib/media'
import { checkAgentAuth } from '@/lib/agent-auth'

export const runtime = 'nodejs'

// Bearer-authed full-image download for the Mac agent (id = attachmentId).
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!checkAgentAuth(req)) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  const att = await db.attachment.findUnique({ where: { id }, select: { path: true } })
  if (!att) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const buf = await readFile(absFromStored(att.path))
  return new NextResponse(new Uint8Array(buf), { headers: { 'Content-Type': 'image/webp' } })
}
