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

export default defineEventHandler(async (event) => {
  requireAuth(event, { role: 'adminOrLeader' })
  const body = await readBody(event).catch(() => ({}))
  const { name, device_type, vendor, lat, lng, stream_url, source_type, config } = validateDeviceBody(body)
  const id = crypto.randomUUID()
  const db = await getDb()
  return withTransaction(db, async ({ run, get }) => {
    await run(
      'INSERT INTO devices (id, name, device_type, vendor, lat, lng, stream_url, source_type, config) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [id, name, device_type, vendor, lat, lng, stream_url, source_type, config],
    )
    const row = await get('SELECT id, name, device_type, vendor, lat, lng, stream_url, source_type, config FROM devices WHERE id = ?', [id])
    const device = rowToDevice(row)
    if (!device) throw createError({ statusCode: 500, message: 'Device not found after insert' })
    return sanitizeDeviceForResponse(device)
  })
})
