import { getDb } from '../../utils/db.js'
import { requireAuth } from '../../utils/authHelpers.js'
import { POI_ICON_TYPES } from '../../utils/validation.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)) || {}
  const updates = {}
  if (typeof body.label === 'string') {
    updates.label = body.label.trim()
  }
  if (POI_ICON_TYPES.includes(body.iconType)) {
    updates.icon_type = body.iconType
  }
  if (Number.isFinite(body.lat)) {
    updates.lat = body.lat
  }
  if (Number.isFinite(body.lng)) {
    updates.lng = body.lng
  }
  if (Object.keys(updates).length === 0) {
    const { get } = await getDb()
    const row = await get('SELECT id, lat, lng, label, icon_type FROM pois WHERE id = ?', [id])
    if (!row) throw createError({ statusCode: 404, message: 'POI not found' })
    return row
  }
  const { run, get } = await getDb()
  const { query, params } = buildUpdateQuery('pois', null, updates)
  if (query) {
    await run(query, [...params, id])
  }
  const row = await get('SELECT id, lat, lng, label, icon_type FROM pois WHERE id = ?', [id])
  if (!row) throw createError({ statusCode: 404, message: 'POI not found' })
  return row
})
