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

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

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

  const { id } = await ctx.params
  const body = await request.json()

  if ('description' in body) {
    const { description, description_lang } = body as { description: string | null; description_lang: 'de' | 'en' }
    const lang = 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_documents SET description_de = $1, description_en = $2, updated_at = NOW()
       WHERE id = $3 RETURNING *`,
      [desc_de, desc_en, id],
    )
    if (rows.length === 0) return NextResponse.json({ error: 'Not found' }, { status: 404 })
    return NextResponse.json({ document: rows[0] })
  }

  const { display_name } = body
  const { rows } = await pool.query(
    `UPDATE dataroom_documents SET display_name = $1, updated_at = NOW()
     WHERE id = $2 RETURNING *`,
    [display_name, id],
  )
  if (rows.length === 0) return NextResponse.json({ error: 'Not found' }, { status: 404 })
  return NextResponse.json({ document: rows[0] })
}

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

  const { id } = await ctx.params
  const admin = await getAdminFromCookie()

  const { rows } = await pool.query(`SELECT * FROM dataroom_documents WHERE id = $1`, [id])
  if (rows.length === 0) return NextResponse.json({ error: 'Not found' }, { status: 404 })

  await pool.query(`DELETE FROM dataroom_documents WHERE id = $1`, [id])
  await removeDir(adminDocDir(id))

  await logAudit(null, 'dataroom_document_deleted', { document_id: id, filename: rows[0].filename }, request, undefined, undefined, admin?.id)
  return NextResponse.json({ success: true })
}
