import { requireAuth } from '../../utils/authHelpers.js'
import { getLiveSession, updateLiveSession } from '../../utils/liveSessions.js'
import { acquire } from '../../utils/asyncLock.js'

export default defineEventHandler(async (event) => {
  const user = requireAuth(event)
  const id = event.context.params?.id
  if (!id) throw createError({ statusCode: 400, message: 'id required' })

  const body = await readBody(event).catch(() => ({}))
  const lat = Number(body?.lat)
  const lng = Number(body?.lng)
  const updates = {}
  if (Number.isFinite(lat)) updates.lat = lat
  if (Number.isFinite(lng)) updates.lng = lng
  if (Object.keys(updates).length === 0) {
    // No updates, just return current session
    const session = getLiveSession(id)
    if (!session) throw createError({ statusCode: 404, message: 'Live session not found' })
    if (session.userId !== user.id) throw createError({ statusCode: 403, message: 'Forbidden' })
    return {
      id: session.id,
      label: session.label,
      lat: session.lat,
      lng: session.lng,
      updatedAt: session.updatedAt,
    }
  }

  // Use lock to atomically check and update session
  return await acquire(`session-patch-${id}`, async () => {
    const session = getLiveSession(id)
    if (!session) throw createError({ statusCode: 404, message: 'Live session not found' })
    if (session.userId !== user.id) throw createError({ statusCode: 403, message: 'Forbidden' })

    try {
      const updated = await updateLiveSession(id, updates)
      // Re-verify after update (updateLiveSession throws if session not found)
      if (!updated || updated.userId !== user.id) {
        throw createError({ statusCode: 404, message: 'Live session not found' })
      }
      return {
        id: updated.id,
        label: updated.label,
        lat: updated.lat,
        lng: updated.lng,
        updatedAt: updated.updatedAt,
      }
    }
    catch (err) {
      if (err.message === 'Session not found') {
        throw createError({ statusCode: 404, message: 'Live session not found' })
      }
      throw err
    }
  })
})
