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 audio download for the Mac agent (id = captureId).
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 capture = await db.capture.findUnique({ where: { id }, select: { audioPath: true, audioMime: true } })
  if (!capture?.audioPath) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const buf = await readFile(absFromStored(capture.audioPath))
  return new NextResponse(new Uint8Array(buf), {
    headers: { 'Content-Type': capture.audioMime || 'application/octet-stream' },
  })
}
