import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { getDependencies, getTwinState } from '@/lib/services/twin-service'

export const dynamic = 'force-dynamic'

/** The scene: placed members, their relationships, and the focus asset's dependencies. */
export const GET = apiRoute<{ code: string }>(
  { permission: 'twin.read' },
  async ({ params, searchParams }) => {
    const state = await getTwinState(params.code)
    if (!state) throw new ApiError(ERROR_CODES.notFound)

    const focus = searchParams.get('focus')?.trim() || state.twin.assetCode
    const dependencies = focus ? await getDependencies(focus) : null

    return {
      twin: state.twin,
      scene: state.scene,
      dependencies,
    }
  },
)
