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

// PUT: Update a pendenz
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string; pendenzId: string }> }) {
  try {
    const { id, pendenzId } = 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 })

    // Verify pendenz belongs to this project
    const existing = await (prisma as any).journalPendenz.findFirst({
      where: { id: pendenzId, projectId: id },
    })
    if (!existing) return NextResponse.json({ error: 'Pendenz nicht gefunden' }, { status: 404 })

    const body = await req.json()
    const data: any = {}
    if (body.what !== undefined) data.what = body.what
    if (body.who !== undefined) data.who = body.who
    if (body.whenHow !== undefined) data.whenHow = body.whenHow
    if (body.done !== undefined) {
      data.done = body.done
      data.doneAt = body.done ? new Date() : null
    }

    const item = await (prisma as any).journalPendenz.update({
      where: { id: pendenzId },
      data,
    })
    return NextResponse.json(item)
  } catch (error) {
    console.error('Error updating pendenz:', error)
    return NextResponse.json({ error: 'Failed to update pendenz' }, { status: 500 })
  }
}

// DELETE
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string; pendenzId: string }> }) {
  try {
    const { id, pendenzId } = 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 })

    // Verify pendenz belongs to this project
    const existing = await (prisma as any).journalPendenz.findFirst({
      where: { id: pendenzId, projectId: id },
    })
    if (!existing) return NextResponse.json({ error: 'Pendenz nicht gefunden' }, { status: 404 })

    await (prisma as any).journalPendenz.delete({ where: { id: pendenzId } })
    return NextResponse.json({ ok: true })
  } catch (error) {
    console.error('Error deleting pendenz:', error)
    return NextResponse.json({ error: 'Failed to delete pendenz' }, { status: 500 })
  }
}
