import { getDb } from '../../utils/db.js'
import { requireAuth } from '../../utils/authHelpers.js'
import { rowToDevice, sanitizeDeviceForResponse, DEVICE_TYPES, SOURCE_TYPES } from '../../utils/deviceUtils.js'
import { buildUpdateQuery } from '../../utils/queryBuilder.js'

export default defineEventHandler(async (event) => {
  requireAuth(event, { role: 'adminOrLeader' })
  const id = event.context.params?.id
  if (!id) throw createError({ statusCode: 400, message: 'id required' })
  const body = (await readBody(event).catch(() => ({}))) || {}
  const updates = {}
  if (typeof body.name === 'string') {
    updates.name = body.name.trim()
  }
  if (DEVICE_TYPES.includes(body.device_type)) {
    updates.device_type = body.device_type
  }
  if (body.vendor !== undefined) {
    updates.vendor = typeof body.vendor === 'string' && body.vendor.trim() ? body.vendor.trim() : null
  }
  if (Number.isFinite(body.lat)) {
    updates.lat = body.lat
  }
  if (Number.isFinite(body.lng)) {
    updates.lng = body.lng
  }
  if (typeof body.stream_url === 'string') {
    updates.stream_url = body.stream_url.trim()
  }
  if (SOURCE_TYPES.includes(body.source_type)) {
    updates.source_type = body.source_type
  }
  if (body.config !== undefined) {
    updates.config = typeof body.config === 'string' ? body.config : (body.config != null ? JSON.stringify(body.config) : null)
  }
  const { run, get } = await getDb()
  if (Object.keys(updates).length === 0) {
    const row = await get('SELECT id, name, device_type, vendor, lat, lng, stream_url, source_type, config FROM devices WHERE id = ?', [id])
    if (!row) throw createError({ statusCode: 404, message: 'Device not found' })
    const device = rowToDevice(row)
    return device ? sanitizeDeviceForResponse(device) : row
  }
  const { query, params } = buildUpdateQuery('devices', null, updates)
  if (query) {
    await run(query, [...params, id])
  }
  const row = await get('SELECT id, name, device_type, vendor, lat, lng, stream_url, source_type, config FROM devices WHERE id = ?', [id])
  if (!row) throw createError({ statusCode: 404, message: 'Device not found' })
  const device = rowToDevice(row)
  return device ? sanitizeDeviceForResponse(device) : row
})
