import { getDb } from '../utils/db.js'
import { requireAuth } from '../utils/authHelpers.js'
import { POI_ICON_TYPES } from '../utils/validation.js'

export default defineEventHandler(async (event) => {
  requireAuth(event, { role: 'adminOrLeader' })
  const body = await readBody(event)
  const lat = Number(body?.lat)
  const lng = Number(body?.lng)
  if (!Number.isFinite(lat) || !Number.isFinite(lng)) throw createError({ statusCode: 400, message: 'lat and lng required as numbers' })
  const label = typeof body?.label === 'string' ? body.label.trim() : ''
  const iconType = POI_ICON_TYPES.includes(body?.iconType) ? body.iconType : 'pin'
  const id = crypto.randomUUID()
  const { run } = await getDb()
  await run(
    'INSERT INTO pois (id, lat, lng, label, icon_type) VALUES (?, ?, ?, ?, ?)',
    [id, lat, lng, label, iconType],
  )
  return { id, lat, lng, label, icon_type: iconType }
})
