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

// GET: List all hose types (global + tenant-specific)
export async function GET() {
  try {
    const user = await getSession()
    if (!user) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 })

    // Show global hose types (tenantId=null) + tenant-specific ones
    const where: any = { isActive: true }
    if (user.role !== 'SERVER_ADMIN' && user.tenantId) {
      where.OR = [{ tenantId: null }, { tenantId: user.tenantId }]
      delete where.isActive
      where.AND = [{ isActive: true }]
    }

    const hoseTypes = await (prisma as any).hoseType.findMany({
      where: user.role === 'SERVER_ADMIN'
        ? { isActive: true }
        : { isActive: true, OR: [{ tenantId: null }, { tenantId: user.tenantId }] },
      orderBy: { sortOrder: 'asc' },
    })
    return NextResponse.json({ hoseTypes })
  } catch (error) {
    console.error('Error fetching hose types:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}

// POST: Create a new hose type (admin only)
export async function POST(request: NextRequest) {
  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, sortOrder } = body

    if (!name || !diameterMm || !flowRateLpm || !frictionCoeff) {
      return NextResponse.json({ error: 'Name, Durchmesser, Durchfluss und Reibungskoeffizient sind erforderlich' }, { status: 400 })
    }

    if (isDefault) {
      await (prisma as any).hoseType.updateMany({ where: { isDefault: true }, data: { isDefault: false } })
    }

    const hoseType = await (prisma as any).hoseType.create({
      data: {
        name,
        diameterMm: parseInt(diameterMm),
        lengthPerPieceM: parseInt(lengthPerPieceM) || 10,
        flowRateLpm: parseFloat(flowRateLpm),
        frictionCoeff: parseFloat(frictionCoeff),
        description: description || null,
        isDefault: isDefault || false,
        sortOrder: sortOrder || 0,
        tenantId: user.role === 'SERVER_ADMIN' ? null : user.tenantId || null,
      },
    })

    return NextResponse.json({ hoseType }, { status: 201 })
  } catch (error: any) {
    if (error.code === 'P2002') {
      return NextResponse.json({ error: 'Ein Schlauchtyp mit diesem Namen existiert bereits' }, { status: 409 })
    }
    console.error('Error creating hose type:', error)
    return NextResponse.json({ error: 'Serverfehler' }, { status: 500 })
  }
}
