import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { twinSnapshotSchema, type TwinSnapshotInput } from '@/lib/api/schemas'
import { createSnapshot } from '@/lib/services/twin-service'

export const dynamic = 'force-dynamic'

/** Freeze the twin (§75). Writes only to `twin_snapshots`; live state is untouched. */
export const POST = apiRoute<{ code: string }, TwinSnapshotInput>(
  { permission: 'twin.snapshot', bodySchema: twinSnapshotSchema, limit: 30 },
  async ({ params, body, user, request }) => {
    const snapshot = await createSnapshot(params.code, {
      reason: body.reason ?? 'manual',
      userId: user.id,
    })
    if (!snapshot) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.twinSnapshot,
      entity: 'digital_twin',
      entityId: params.code,
      user,
      request,
      detail: `${snapshot.code}: ${snapshot.assetCount} members, peak risk ${snapshot.peakRisk} %`,
    })

    return snapshot
  },
)
