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

export default defineEventHandler(async (event) => {
  requireAuth(event)
  const id = event.context.params?.id
  if (!id) throw createError({ statusCode: 400, message: 'id required' })
  const { get } = await getDb()
  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)
  if (!device) throw createError({ statusCode: 500, message: 'Invalid device row' })
  return sanitizeDeviceForResponse(device)
})
