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 PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const authResult = await requireAuth(['ADMIN'])(request)
    if ('error' in authResult) return authResult.error

    const { user } = authResult
    const { id } = await params

    // Admin cannot modify their own account from here
    if (id === user.id) {
      return NextResponse.json(
        { error: 'No puede modificar su propia cuenta desde aquí' },
        { status: 400 }
      )
    }

    const body = await request.json()

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

    if (!target) {
      return NextResponse.json(
        { error: 'Administrador 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)
    if (body.isActive !== undefined) 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({ admin: updated })
  } catch (error) {
    console.error('Error:', error)
    return NextResponse.json({ error: 'Error interno' }, { 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 { user } = authResult
    const { id } = await params

    // Admin cannot deactivate their own account
    if (id === user.id) {
      return NextResponse.json(
        { error: 'No puede desactivar su propia cuenta' },
        { status: 400 }
      )
    }

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

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

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

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