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 mini (id = digestReplyId). Mirrors
// /api/agent/audio/[id], which does the same for captures — whisper runs there,
// so the bytes have to travel.
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 row = await db.digestReply.findUnique({ where: { id }, select: { audioPath: true, audioMime: true } })
  if (!row?.audioPath) return NextResponse.json({ error: 'not found' }, { status: 404 })

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