import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { investorUploadDir, saveFile, safeName } from '@/lib/dataroom-storage'
import { logAudit, getSessionFromCookie } from '@/lib/auth'
import { translateText } from '@/lib/translate'
import { randomUUID } from 'crypto'

export const dynamic = 'force-dynamic'

const MAX_BYTES = parseInt(process.env.DATAROOM_MAX_UPLOAD_MB || '50') * 1024 * 1024

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

  const { rows } = await pool.query(
    `SELECT id, filename, display_name, description_de, description_en, mime_type, file_size, created_at
     FROM dataroom_investor_uploads
     WHERE investor_id = $1
     ORDER BY created_at DESC`,
    [investorId],
  )
  return NextResponse.json({ uploads: rows })
}

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

  const formData = await request.formData()
  const files = formData.getAll('file') as File[]
  const validFiles = files.filter(f => f && f.size > 0)
  if (validFiles.length === 0) return NextResponse.json({ error: 'No files provided' }, { status: 400 })

  const oversized = validFiles.find(f => f.size > MAX_BYTES)
  if (oversized) return NextResponse.json({ error: `File "${oversized.name}" exceeds ${process.env.DATAROOM_MAX_UPLOAD_MB || 50}MB limit` }, { status: 413 })

  const description = (formData.get('description') as string | null) || null
  const descLang = (formData.get('description_lang') as 'de' | 'en' | null) || 'en'

  let desc_de: string | null = null
  let desc_en: string | null = null
  if (description) {
    const translated = await translateText(description, descLang)
    desc_de = descLang === 'de' ? description : (translated || null)
    desc_en = descLang === 'en' ? description : (translated || null)
  }

  const inserted = []
  for (const file of validFiles) {
    const uploadId = randomUUID()
    const filename = safeName(file.name)
    const buffer = Buffer.from(await file.arrayBuffer())
    const filePath = await saveFile(investorUploadDir(investorId, uploadId), filename, buffer)

    const { rows } = await pool.query(
      `INSERT INTO dataroom_investor_uploads
         (id, investor_id, filename, file_path, display_name, description_de, description_en, mime_type, file_size)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
       RETURNING id, filename, display_name, description_de, description_en, mime_type, file_size, created_at`,
      [uploadId, investorId, filename, filePath, file.name, desc_de, desc_en,
       file.type || 'application/octet-stream', file.size],
    )
    await logAudit(investorId, 'dataroom_investor_uploaded', { upload_id: uploadId, filename, file_size: file.size }, request, undefined, sessionId)
    inserted.push(rows[0])
  }

  return NextResponse.json({ uploads: inserted }, { status: 201 })
}
