import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { streamFile } from '@/lib/dataroom-storage'
import { logAudit, getSessionFromCookie } from '@/lib/auth'
import path from 'path'

interface Ctx { params: Promise<{ id: string }> }

export async function GET(request: NextRequest, ctx: Ctx) {
  const session = await getSessionFromCookie()
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  const investorId = session.sub
  const sessionId = session.sessionId

  const { id } = await ctx.params

  // Verify investor has a release for this document
  const { rows } = await pool.query(
    `SELECT d.file_path, d.filename, d.mime_type, d.display_name
     FROM dataroom_releases r
     JOIN dataroom_documents d ON d.id = r.document_id
     WHERE r.investor_id = $1 AND d.id = $2`,
    [investorId, id],
  )
  if (rows.length === 0) return NextResponse.json({ error: 'Not found' }, { status: 404 })

  const doc = rows[0]

  await logAudit(investorId, 'dataroom_document_downloaded', { document_id: id, filename: doc.filename }, request, undefined, sessionId ?? undefined)

  const { stream, size } = await streamFile(doc.file_path)
  const disposition = request.nextUrl.searchParams.get('preview') === '1' ? 'inline' : 'attachment'

  return new Response(stream, {
    headers: {
      'Content-Type': doc.mime_type || 'application/octet-stream',
      'Content-Disposition': `${disposition}; filename="${path.basename(doc.filename)}"`,
      'Content-Length': String(size),
    },
  })
}
