import { updateLote } from '../../utils/queries'

/**
 * PATCH /api/lotes/:id
 * Actualiza un lote existente
 *
 * Body (todos opcionales):
 * {
 *   codigo?: string | null,
 *   tipo?: string,
 *   cantidad_kg?: number | null,
 *   lugar_id?: number | null,
 *   meta?: object | null
 * }
 */
export default defineEventHandler(async (event) => {
  try {
    const id = getRouterParam(event, 'id')

    if (!id) {
      throw createError({
        statusCode: 400,
        statusMessage: 'ID de lote requerido',
      })
    }

    const body = await readBody(event)

    const lote = await updateLote(id, body)

    if (!lote) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Lote no encontrado',
      })
    }

    return {
      success: true,
      data: lote,
    }
  } catch (error: any) {
    console.error('Error actualizando lote:', error)

    if (error.statusCode) {
      throw error
    }

    throw createError({
      statusCode: 500,
      statusMessage: 'Error actualizando lote',
      data: { message: error.message },
    })
  }
})
