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

export const dynamic = 'force-dynamic'

export async function GET(request: NextRequest) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response

  const { rows } = await pool.query(
    `SELECT d.id, d.filename, d.display_name, d.description_de, d.description_en,
            d.mime_type, d.file_size, d.uploaded_by, d.created_at,
            COUNT(r.id)::int AS release_count
     FROM dataroom_documents d
     LEFT JOIN dataroom_releases r ON r.document_id = d.id
     GROUP BY d.id
     ORDER BY d.created_at DESC`,
  )
  return NextResponse.json({ documents: rows })
}

export async function POST(request: NextRequest) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response

  const admin = await getAdminFromCookie()
  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 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 documentId = randomUUID()
    const filename = safeName(file.name)
    const buffer = Buffer.from(await file.arrayBuffer())
    const filePath = await saveFile(adminDocDir(documentId), filename, buffer)

    const { rows } = await pool.query(
      `INSERT INTO dataroom_documents
         (id, filename, file_path, display_name, description_de, description_en, mime_type, file_size, uploaded_by)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
       RETURNING *`,
      [documentId, filename, filePath, file.name, desc_de, desc_en,
       file.type || 'application/octet-stream', file.size, admin?.email ?? 'admin'],
    )
    await logAudit(null, 'dataroom_document_uploaded', { document_id: documentId, filename, file_size: file.size }, request, undefined, undefined, admin?.id)
    inserted.push(rows[0])
  }

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