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

// PUT: Update a journal entry — only toggle done status allowed directly
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string; entryId: string }> }) {
  try {
    const { id, entryId } = 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).journalEntry.findFirst({
      where: { id: entryId, projectId: id },
    })
    if (!existing) return NextResponse.json({ error: 'Eintrag nicht gefunden' }, { status: 404 })

    const body = await req.json()

    // Only done toggle is allowed as direct edit
    if (body.done !== undefined) {
      const entry = await (prisma as any).journalEntry.update({
        where: { id: entryId },
        data: { done: body.done, doneAt: body.done ? new Date() : null },
      })
      return NextResponse.json(entry)
    }

    return NextResponse.json({ error: 'Direkte Bearbeitung nicht erlaubt. Bitte Korrektur erstellen.' }, { status: 400 })
  } catch (error) {
    console.error('Error updating journal entry:', error)
    return NextResponse.json({ error: 'Failed to update entry' }, { status: 500 })
  }
}

// POST: Create a correction for a journal entry (replaces DELETE)
// Marks the original as corrected (strikethrough) and creates a new correction entry below it
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string; entryId: string }> }) {
  try {
    const { id, entryId } = 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).journalEntry.findFirst({
      where: { id: entryId, projectId: id },
    })
    if (!existing) return NextResponse.json({ error: 'Eintrag nicht gefunden' }, { status: 404 })

    // Prevent double-correction or correcting a correction entry
    if (existing.isCorrected) {
      return NextResponse.json({ error: 'Dieser Eintrag wurde bereits korrigiert.' }, { status: 400 })
    }
    if (existing.correctionOfId) {
      return NextResponse.json({ error: 'Ein Korrektureintrag kann nicht nochmals korrigiert werden.' }, { status: 400 })
    }

    const body = await req.json()
    const correctionText = body.what || ''

    if (!correctionText.trim()) {
      return NextResponse.json({ error: 'Korrekturtext ist erforderlich' }, { status: 400 })
    }

    // Mark original as corrected
    await (prisma as any).journalEntry.update({
      where: { id: entryId },
      data: { isCorrected: true },
    })

    // Create correction entry with same time, placed right after the original
    const correction = await (prisma as any).journalEntry.create({
      data: {
        time: existing.time,
        what: `[Korrektur] ${correctionText}`,
        who: body.who || existing.who || user.name,
        sortOrder: existing.sortOrder + 1,
        correctionOfId: existing.id,
        projectId: id,
      },
    })

    return NextResponse.json({ original: existing, correction })
  } catch (error) {
    console.error('Error creating correction:', error)
    return NextResponse.json({ error: 'Failed to create correction' }, { status: 500 })
  }
}

// DELETE: Not allowed — entries cannot be deleted, only corrected
export async function DELETE() {
  return NextResponse.json(
    { error: 'Journal-Einträge können nicht gelöscht werden. Bitte erstellen Sie eine Korrektur.' },
    { status: 403 }
  )
}
