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

export const dynamic = 'force-dynamic'

/** One twin's identity, mode and recent activity. */
export const GET = apiRoute<{ code: string }>({ permission: 'twin.read' }, async ({ params }) => {
  const twin = await getTwinRecord(params.code)
  if (!twin) throw new ApiError(ERROR_CODES.notFound)

  const [snapshots, simulations] = await Promise.all([
    listSnapshots(twin.code, 5),
    listTwinSimulations(twin.code, 5),
  ])

  return {
    twin,
    // Stated on every twin response: this build observes and simulates, never controls.
    autonomy: { level: twin.autonomyLevel, max: 3, canExecute: false },
    snapshots: snapshots.map((snapshot) => ({
      code: snapshot.code,
      ts: snapshot.ts.getTime(),
      reason: snapshot.reason,
      peakRisk: snapshot.peakRisk,
      stabilityIndex: snapshot.stabilityIndex,
    })),
    simulations: simulations.map((simulation) => ({
      code: simulation.code,
      createdAt: simulation.createdAt.getTime(),
      riskBefore: simulation.riskBefore,
      riskAfter: simulation.riskAfter,
      summary: simulation.summary,
      summaryAr: simulation.summaryAr,
    })),
  }
})
