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', 'MANAGER'])(request)
    if ('error' in authResult) return authResult.error

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

    // id = customer userId, body.supervisorId = new supervisor
    const customer = await db.user.findFirst({
      where: { id, role: 'CUSTOMER' },
    })

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

    if (body.supervisorId) {
      const supervisor = await db.user.findFirst({
        where: { id: body.supervisorId, role: 'SUPERVISOR', isActive: true },
      })
      if (!supervisor) {
        return NextResponse.json(
          { error: 'Supervisor no encontrado o inactivo' },
          { status: 404 }
        )
      }
    }

    const updated = await db.user.update({
      where: { id },
      data: { assignedById: body.supervisorId || null },
      select: {
        id: true,
        name: true,
        email: true,
        assignedById: true,
        assignedBy: { select: { id: true, name: true } },
      },
    })

    // Also reassign any PENDING/ACKNOWLEDGED reviews from old supervisor to new one
    if (body.supervisorId) {
      await db.review.updateMany({
        where: {
          customerId: id,
          status: { in: ['PENDING', 'ACKNOWLEDGED'] },
          deletedAt: null,
        },
        data: { assignedToId: body.supervisorId },
      })
    }

    return NextResponse.json({
      customer: updated,
      message: 'Asignación actualizada',
    })
  } catch (error) {
    console.error('Error:', error)
    return NextResponse.json(
      { error: 'Error interno del servidor' },
      { status: 500 }
    )
  }
}
