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

/** Zeile eines Tabellen-Moduls aktualisieren (data wird gemerged) */
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; moduleId: string; itemId: string }> }
) {
  try {
    const { id, moduleId, itemId } = await params
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
    if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })

    const project = await getProjectWithTenantCheck(id, user)
    if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })

    const existing = await (prisma as any).moduleItem.findFirst({
      where: { id: itemId, projectId: id, moduleId },
    })
    if (!existing) return NextResponse.json({ error: 'Eintrag nicht gefunden' }, { status: 404 })

    const body = await request.json()
    const patch = body && typeof body.data === 'object' && body.data !== null ? body.data : {}

    const merged = { ...(existing.data || {}), ...patch }
    // Payload-Härtung: Zeilengrösse begrenzen (DB-Bloat/DoS vermeiden)
    if (JSON.stringify(merged).length > 20000) {
      return NextResponse.json({ error: 'Eintrag zu gross' }, { status: 413 })
    }

    const item = await (prisma as any).moduleItem.update({
      where: { id: itemId },
      data: { data: merged },
    })
    return NextResponse.json(item)
  } catch (error) {
    console.error('Error updating module item:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}

/** Zeile eines Tabellen-Moduls löschen */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; moduleId: string; itemId: string }> }
) {
  try {
    const { id, moduleId, itemId } = await params
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
    if (user.role === 'VIEWER') return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })

    const project = await getProjectWithTenantCheck(id, user)
    if (!project) return NextResponse.json({ error: 'Projekt nicht gefunden' }, { status: 404 })

    await (prisma as any).moduleItem.deleteMany({
      where: { id: itemId, projectId: id, moduleId },
    })
    return NextResponse.json({ ok: true })
  } catch (error) {
    console.error('Error deleting module item:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
