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

// PUT: Update a hose type
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
    if (user.role !== 'SERVER_ADMIN' && user.role !== 'TENANT_ADMIN') {
      return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
    }

    const body = await request.json()
    const { name, diameterMm, lengthPerPieceM, flowRateLpm, frictionCoeff, description, isDefault, isActive, sortOrder } = body

    // If setting as default, unset other defaults
    if (isDefault) {
      await prisma.hoseType.updateMany({
        where: { isDefault: true, id: { not: params.id } },
        data: { isDefault: false },
      })
    }

    const hoseType = await prisma.hoseType.update({
      where: { id: params.id },
      data: {
        ...(name !== undefined && { name }),
        ...(diameterMm !== undefined && { diameterMm: parseInt(diameterMm) }),
        ...(lengthPerPieceM !== undefined && { lengthPerPieceM: parseInt(lengthPerPieceM) }),
        ...(flowRateLpm !== undefined && { flowRateLpm: parseFloat(flowRateLpm) }),
        ...(frictionCoeff !== undefined && { frictionCoeff: parseFloat(frictionCoeff) }),
        ...(description !== undefined && { description }),
        ...(isDefault !== undefined && { isDefault }),
        ...(isActive !== undefined && { isActive }),
        ...(sortOrder !== undefined && { sortOrder }),
      },
    })

    return NextResponse.json({ hoseType })
  } catch (error: any) {
    if (error.code === 'P2025') {
      return NextResponse.json({ error: 'Schlauchtyp nicht gefunden' }, { status: 404 })
    }
    console.error('Error updating hose type:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}

// DELETE: Delete a hose type
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })
    if (user.role !== 'SERVER_ADMIN' && user.role !== 'TENANT_ADMIN') {
      return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 })
    }

    await prisma.hoseType.delete({ where: { id: params.id } })
    return NextResponse.json({ success: true })
  } catch (error: any) {
    if (error.code === 'P2025') {
      return NextResponse.json({ error: 'Schlauchtyp nicht gefunden' }, { status: 404 })
    }
    console.error('Error deleting hose type:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
