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

// PUT: Toggle confirmed/ok on a check item
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string; itemId: string }> }) {
  try {
    const { id, 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 })

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

    const body = await req.json()
    const data: any = {}
    if (body.label !== undefined) data.label = body.label
    if (body.confirmed !== undefined) {
      data.confirmed = body.confirmed
      data.confirmedAt = body.confirmed ? new Date() : null
    }
    if (body.ok !== undefined) {
      data.ok = body.ok
      data.okAt = body.ok ? new Date() : null
    }

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

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

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

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