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

// GET: Liste aller Übungsziele eines Projekts
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = 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 goals = await (prisma as any).exerciseGoal.findMany({
      where: { projectId: id },
      orderBy: { sortOrder: 'asc' },
    })
    return NextResponse.json({ goals })
  } catch (error) {
    console.error('Error fetching exercise goals:', error)
    return NextResponse.json({ error: 'Failed to fetch goals' }, { status: 500 })
  }
}

// POST: Neues Übungsziel anlegen
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = 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 body = await req.json()
    if (!body.text || !String(body.text).trim()) {
      return NextResponse.json({ error: 'Text erforderlich' }, { status: 400 })
    }

    // Ans Ende der Liste einsortieren
    const last = await (prisma as any).exerciseGoal.findFirst({
      where: { projectId: id },
      orderBy: { sortOrder: 'desc' },
      select: { sortOrder: true },
    })

    const goal = await (prisma as any).exerciseGoal.create({
      data: {
        projectId: id,
        text: String(body.text).trim(),
        status: 'OPEN',
        sortOrder: (last?.sortOrder ?? -1) + 1,
      },
    })
    return NextResponse.json({ goal })
  } catch (error) {
    console.error('Error creating exercise goal:', error)
    return NextResponse.json({ error: 'Failed to create goal' }, { status: 500 })
  }
}
