import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getSession, isAdmin } from '@/lib/auth'

// DELETE: Remove a dictionary word
export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const user = await getSession()
    if (!user || !isAdmin(user.role)) {
      return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 403 })
    }

    const entry = await (prisma as any).dictionaryEntry.findUnique({
      where: { id: params.id },
    })

    if (!entry) {
      return NextResponse.json({ error: 'Eintrag nicht gefunden' }, { status: 404 })
    }

    // Only SERVER_ADMIN can delete global words
    if (entry.scope === 'GLOBAL' && user.role !== 'SERVER_ADMIN') {
      return NextResponse.json({ error: 'Nur Server-Admin kann globale Wörter löschen' }, { status: 403 })
    }

    // TENANT_ADMIN can only delete their own tenant's words
    if (entry.scope === 'TENANT' && entry.tenantId !== user.tenantId && user.role !== 'SERVER_ADMIN') {
      return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
    }

    await (prisma as any).dictionaryEntry.delete({ where: { id: params.id } })
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Error deleting dictionary word:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
