import { apiRoute } from '@/lib/api/handler'
import { getEnvelope, getFleetEnvelopes } from '@/lib/services/physics-service'

export const dynamic = 'force-dynamic'

/**
 * Operating envelopes (§12, §13).
 *
 * With `asset`, one envelope; without, the tightest in the fleet — least headroom first,
 * because the question this answers is "what is closest to its ceiling", not "list
 * everything".
 */
export const GET = apiRoute({ permission: 'physics.read' }, async ({ searchParams }) => {
  const assetCode = searchParams.get('asset')
  if (assetCode) {
    const envelope = await getEnvelope(assetCode)
    return { envelope }
  }

  const limit = Math.min(50, Math.max(1, Number(searchParams.get('limit')) || 12))
  return { envelopes: await getFleetEnvelopes({ limit }) }
})
