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

export async function GET(
  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 supervisor = await db.user.findFirst({
      where: { id, role: 'SUPERVISOR' },
      select: {
        id: true,
        email: true,
        name: true,
        phone: true,
        role: true,
        isActive: true,
        createdAt: true,
        _count: {
          select: { customers: true, assignedReviews: true },
        },
      },
    })

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

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

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 { user } = authResult
    const { id } = await params
    const body = await request.json()

    const supervisor = await db.user.findFirst({
      where: { id, role: 'SUPERVISOR' },
    })

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

    const data: Record<string, unknown> = {}

    if (body.name) data.name = body.name.trim()
    if (body.email) data.email = body.email.trim()
    if (body.phone !== undefined) data.phone = body.phone?.trim() || null
    if (body.password) data.passwordHash = await hashPassword(body.password)
    // Only ADMIN can toggle isActive
    if (body.isActive !== undefined && user.role === 'ADMIN')
      data.isActive = body.isActive

    const updated = await db.user.update({
      where: { id },
      data,
      select: {
        id: true,
        email: true,
        name: true,
        phone: true,
        role: true,
        isActive: true,
      },
    })

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

export async function DELETE(
  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 supervisor = await db.user.findFirst({
      where: { id, role: 'SUPERVISOR' },
    })

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

    const updated = await db.user.update({
      where: { id },
      data: { isActive: !supervisor.isActive },
      select: { id: true, name: true, isActive: true },
    })

    return NextResponse.json({
      supervisor: updated,
      message: updated.isActive
        ? 'Supervisor reactivado'
        : 'Supervisor desactivado',
    })
  } catch (error) {
    console.error('Error:', error)
    return NextResponse.json(
      { error: 'Error interno del servidor' },
      { status: 500 }
    )
  }
}
