import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { requireAdmin } from '@/lib/admin-auth'
import { streamFile } from '@/lib/dataroom-storage'
import { translateText } from '@/lib/translate'
import path from 'path'

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

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

  const { id: investorId } = await ctx.params
  const download = request.nextUrl.searchParams.get('download')

  if (download) {
    const { rows } = await pool.query(
      `SELECT file_path, filename, mime_type FROM dataroom_investor_uploads
       WHERE id = $1 AND investor_id = $2`,
      [download, investorId],
    )
    if (rows.length === 0) return NextResponse.json({ error: 'Not found' }, { status: 404 })
    const { stream, size } = await streamFile(rows[0].file_path)
    return new Response(stream, {
      headers: {
        'Content-Type': rows[0].mime_type || 'application/octet-stream',
        'Content-Disposition': `attachment; filename="${path.basename(rows[0].filename)}"`,
        'Content-Length': String(size),
      },
    })
  }

  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 PATCH(request: NextRequest, ctx: Ctx) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response

  const { id: investorId } = await ctx.params
  const { upload_id, description, description_lang } = await request.json()
  const lang: 'de' | 'en' = description_lang || 'en'

  const translated = description ? await translateText(description, lang) : null
  const desc_de = lang === 'de' ? (description || null) : translated
  const desc_en = lang === 'en' ? (description || null) : translated

  const { rows } = await pool.query(
    `UPDATE dataroom_investor_uploads SET description_de = $1, description_en = $2
     WHERE id = $3 AND investor_id = $4
     RETURNING id, filename, display_name, description_de, description_en, mime_type, file_size, created_at`,
    [desc_de, desc_en, upload_id, investorId],
  )
  if (rows.length === 0) return NextResponse.json({ error: 'Not found' }, { status: 404 })
  return NextResponse.json({ upload: rows[0] })
}
