import { NextRequest, NextResponse } from 'next/server'
import { requireAdmin } from '@/lib/adminAuth'
import { prisma } from '@/lib/prisma'

export async function PUT(req: NextRequest, { params }: { params: { id: string } }) {
  const auth = await requireAdmin()
  if ('error' in auth) return auth.error

  const userId = parseInt(params.id)
  if (isNaN(userId)) return NextResponse.json({ error: 'ID inválido' }, { status: 400 })

  const body = await req.json()
  const { role, active, businessLines } = body as {
    role: string
    active: boolean
    businessLines: number[]
  }

  await prisma.$transaction([
    prisma.user.update({
      where: { id: userId },
      data: { role: role as Parameters<typeof prisma.user.update>[0]['data']['role'], active },
    }),
    prisma.userBusinessLine.deleteMany({ where: { userId } }),
    ...(businessLines.length > 0
      ? [
          prisma.userBusinessLine.createMany({
            data: businessLines.map((blId) => ({ userId, businessLineId: blId })),
          }),
        ]
      : []),
  ])

  await prisma.auditLog.create({
    data: {
      userId: auth.userId,
      action: 'UPDATE_USER',
      entity: 'User',
      entityId: userId,
      details: `rol=${role}, activo=${active}`,
    },
  })

  return NextResponse.json({ ok: true })
}
