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'

/** Snapshots and simulation runs, which together are the twin's audit trail (§75, §87). */
export const GET = apiRoute<{ code: string }>(
  { permission: 'twin.read' },
  async ({ params, searchParams }) => {
    const twin = await getTwinRecord(params.code)
    if (!twin) throw new ApiError(ERROR_CODES.notFound)

    const limit = Math.min(50, Math.max(1, Number(searchParams.get('limit')) || 20))
    const [snapshots, simulations] = await Promise.all([
      listSnapshots(twin.code, limit),
      listTwinSimulations(twin.code, limit),
    ])

    return {
      twin,
      snapshots: snapshots.map((snapshot) => ({
        code: snapshot.code,
        ts: snapshot.ts.getTime(),
        reason: snapshot.reason,
        assetCount: snapshot.assetCount,
        totalLoadMw: snapshot.totalLoadMw,
        stabilityIndex: snapshot.stabilityIndex,
        peakRisk: snapshot.peakRisk,
        perturbation: snapshot.perturbation,
      })),
      simulations: simulations.map((simulation) => ({
        code: simulation.code,
        createdAt: simulation.createdAt.getTime(),
        durationMs: simulation.durationMs,
        horizonMin: simulation.horizonMin,
        riskBefore: simulation.riskBefore,
        riskAfter: simulation.riskAfter,
        stabilityBefore: simulation.stabilityBefore,
        stabilityAfter: simulation.stabilityAfter,
        assetsAffected: simulation.assetsAffected,
        downtimeMin: simulation.downtimeMin,
        summary: simulation.summary,
        summaryAr: simulation.summaryAr,
      })),
    }
  },
)
