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

const ALLOWED_STATUS = ['OPEN', 'REACHED', 'PARTIAL', 'MISSED']

// PUT: Übungsziel aktualisieren (Text / Status / Notiz)
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string; goalId: string }> }) {
  try {
    const { id, goalId } = 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).exerciseGoal.findFirst({
      where: { id: goalId, projectId: id },
    })
    if (!existing) return NextResponse.json({ error: 'Ziel nicht gefunden' }, { status: 404 })

    const body = await req.json()
    const data: any = {}
    if (body.text !== undefined) data.text = String(body.text).trim()
    if (body.note !== undefined) data.note = body.note || null
    if (body.status !== undefined) {
      if (!ALLOWED_STATUS.includes(body.status)) {
        return NextResponse.json({ error: 'Ungültiger Status' }, { status: 400 })
      }
      data.status = body.status
    }
    if (body.sortOrder !== undefined) data.sortOrder = body.sortOrder

    const goal = await (prisma as any).exerciseGoal.update({
      where: { id: goalId },
      data,
    })
    return NextResponse.json({ goal })
  } catch (error) {
    console.error('Error updating exercise goal:', error)
    return NextResponse.json({ error: 'Failed to update goal' }, { status: 500 })
  }
}

// DELETE: Übungsziel löschen
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string; goalId: string }> }) {
  try {
    const { id, goalId } = 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).exerciseGoal.findFirst({
      where: { id: goalId, projectId: id },
    })
    if (!existing) return NextResponse.json({ error: 'Ziel nicht gefunden' }, { status: 404 })

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