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

export const dynamic = 'force-dynamic'

/**
 * The twin's state now (§30, §32).
 *
 * Read-only and free of any scenario: this endpoint is the shadow view, and the response
 * says `source: "live"` so a caller cannot mistake it for a simulation result.
 */
export const GET = apiRoute<{ code: string }>(
  { permission: 'twin.read', limit: 120 },
  async ({ params }) => {
    const state = await getTwinState(params.code)
    if (!state) throw new ApiError(ERROR_CODES.notFound)

    return {
      twin: state.twin,
      ts: state.ts,
      source: state.source,
      snapshot: state.snapshot,
      fidelity: state.fidelity,
      assets: state.assets,
    }
  },
)
