import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { getSessionFromCookie } from '@/lib/auth'
import { translateText } from '@/lib/translate'

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

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

  const { id } = await ctx.params
  const { 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, id, session.sub],
  )
  if (rows.length === 0) return NextResponse.json({ error: 'Not found' }, { status: 404 })
  return NextResponse.json({ upload: rows[0] })
}
