import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { getResilience } from '@/lib/services/resilience-service'
import { getTwinRecord } from '@/lib/services/twin-service'

export const dynamic = 'force-dynamic'

/** The resilience score and safe operating envelope for this twin's scope (§39, §41). */
export const GET = apiRoute<{ code: string }>(
  { permission: 'twin.read', limit: 30 },
  async ({ params, searchParams }) => {
    const twin = await getTwinRecord(params.code)
    if (!twin) throw new ApiError(ERROR_CODES.notFound)

    const includeEnvelope = searchParams.get('envelope') !== 'false'
    const resilience = await getResilience({ includeEnvelope })
    return { twin, ...resilience }
  },
)
