import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { requireAuth } from '@/lib/api-auth'

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResult = await requireAuth(['ADMIN'])(request)
    if ('error' in authResult) return authResult.error

    const { id } = await params
    const body = await request.json()
    const { supervisorId } = body

    // Verify the target user is a CUSTOMER
    const customer = await db.user.findUnique({
      where: { id },
    })

    if (!customer) {
      return NextResponse.json(
        { error: 'Usuario no encontrado' },
        { status: 404 }
      )
    }

    if (customer.role !== 'CUSTOMER') {
      return NextResponse.json(
        { error: 'El usuario no es un cliente' },
        { status: 400 }
      )
    }

    // If supervisorId is provided, verify it's a valid SUPERVISOR
    if (supervisorId !== null && supervisorId !== undefined) {
      const supervisor = await db.user.findUnique({
        where: { id: supervisorId },
      })

      if (!supervisor) {
        return NextResponse.json(
          { error: 'Supervisor no encontrado' },
          { status: 404 }
        )
      }

      if (supervisor.role !== 'SUPERVISOR') {
        return NextResponse.json(
          { error: 'El usuario asignado no es un supervisor' },
          { status: 400 }
        )
      }

      if (!supervisor.isActive) {
        return NextResponse.json(
          { error: 'El supervisor no está activo' },
          { status: 400 }
        )
      }
    }

    // Update the customer's assigned supervisor
    const updated = await db.user.update({
      where: { id },
      data: { assignedById: supervisorId || null },
      select: {
        id: true,
        email: true,
        name: true,
        company: true,
        phone: true,
        role: true,
        isActive: true,
        createdAt: true,
        assignedBy: { select: { id: true, name: true, email: true } },
      },
    })

    return NextResponse.json({ customer: updated })
  } catch (error) {
    console.error('Error al asignar supervisor:', error)
    return NextResponse.json(
      { error: 'Error interno del servidor' },
      { status: 500 }
    )
  }
}
