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

/** Zeilen eines Tabellen-Moduls laden */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; moduleId: string }> }
) {
  try {
    const { id, moduleId } = await params
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

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

    const items = await (prisma as any).moduleItem.findMany({
      where: { projectId: id, moduleId },
      orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }],
    })
    return NextResponse.json({ items })
  } catch (error) {
    console.error('Error fetching module items:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}

/** Neue Zeile in einem Tabellen-Modul anlegen */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; moduleId: string }> }
) {
  try {
    const { id, moduleId } = 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 })

    if (moduleId.length > 64) return NextResponse.json({ error: 'Ungültige Modul-ID' }, { status: 400 })

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

    const body = await request.json()
    const data = body && typeof body.data === 'object' && body.data !== null ? body.data : {}
    // Payload-Härtung: eine Tabellenzeile bleibt klein — verhindert DB-Bloat/DoS
    if (JSON.stringify(data).length > 20000) {
      return NextResponse.json({ error: 'Eintrag zu gross' }, { status: 413 })
    }

    const count = await (prisma as any).moduleItem.count({ where: { projectId: id, moduleId } })
    const item = await (prisma as any).moduleItem.create({
      data: { projectId: id, moduleId, data, sortOrder: count },
    })
    return NextResponse.json(item, { status: 201 })
  } catch (error) {
    console.error('Error creating module item:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
