import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createWebCadFacade } from '../src/facade/mockFacade'
import type { DocumentSnapshot, FacadeEvent } from '../src/facade/types'

const fixture = (): DocumentSnapshot => ({
  id: 'property-acceleration-transaction',
  label: 'PropertyAcceleration Transaction',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [{ id: 'AccelerationProbe', label: 'Acceleration probe', type: 'feature', state: 'valid' }],
  objects: [{
    id: 'AccelerationProbe',
    typeId: 'Robot::TrajectoryDressUpObject',
    properties: [{ name: 'Acceleration', label: 'Acceleration', group: 'TrajectoryDressUp', scope: 'data', type: 'App::PropertyAcceleration', value: 1000, unit: 'mm/s^2', recompute: true }],
  }],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { AccelerationProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

const acceleration = (facade: ReturnType<typeof createWebCadFacade>) => facade.app.document.getObject('AccelerationProbe')?.properties.find((property) => property.name === 'Acceleration')?.value

test('App::PropertyAcceleration transaction closes undo, redo, abort, stale, failure and resource ownership', () => {
  const facade = createWebCadFacade({ initialDocument: fixture(), runtimeMode: 'mock' })
  const events: FacadeEvent[] = []
  facade.subscribe((event) => {
    if (event.type === 'property.before-change' || event.type === 'property.changed' || event.type === 'transaction.committed') events.push(event)
  })
  const resourcesBefore = facade.geometry.capabilities()

  facade.app.document.setProperty({ objectId: 'AccelerationProbe', propertyName: 'Acceleration', value: 500, expectedDocumentVersion: 1 })
  assert.equal(acceleration(facade), 500)
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.history.canUndo(), true)
  assert.equal(facade.history.canRedo(), false)
  assert.deepEqual(events.map((event) => event.type), ['property.before-change', 'property.changed', 'transaction.committed'])
  const transactionIds = events.map((event) => 'transactionId' in event ? event.transactionId : '')
  assert.equal(new Set(transactionIds).size, 1)
  const committed = events[2]
  assert.equal(committed.type, 'transaction.committed')
  if (committed.type === 'transaction.committed') assert.deepEqual({ operation: committed.operation, beforeVersion: committed.beforeVersion, afterVersion: committed.afterVersion }, { operation: 'property.set', beforeVersion: 1, afterVersion: 2 })

  facade.history.undo()
  assert.equal(acceleration(facade), 1000)
  assert.equal(facade.app.document.getActive().version, 1)
  assert.equal(facade.history.canUndo(), false)
  assert.equal(facade.history.canRedo(), true)
  facade.history.redo()
  assert.equal(acceleration(facade), 500)
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.history.canUndo(), true)
  assert.equal(facade.history.canRedo(), false)

  const stableState = JSON.stringify(facade.app.document.getActive())
  const stableEvents = events.length
  assert.throws(() => facade.app.document.setProperty({ objectId: 'AccelerationProbe', propertyName: 'Acceleration', value: 250, expectedDocumentVersion: 1 }), /Stale document version: expected 1, current 2/)
  assert.equal(JSON.stringify(facade.app.document.getActive()), stableState)
  assert.equal(events.length, stableEvents)

  const cancelled = new AbortController()
  cancelled.abort()
  assert.throws(() => facade.app.document.setProperty({ objectId: 'AccelerationProbe', propertyName: 'Acceleration', value: 250, expectedDocumentVersion: 2, signal: cancelled.signal }), (error: unknown) => error instanceof DOMException && error.name === 'AbortError')
  assert.equal(JSON.stringify(facade.app.document.getActive()), stableState)
  assert.equal(events.length, stableEvents)

  assert.throws(() => facade.app.document.setProperty({ objectId: 'AccelerationProbe', propertyName: 'Acceleration', value: 'invalid' }), /finite numeric value/)
  assert.equal(JSON.stringify(facade.app.document.getActive()), stableState)
  assert.equal(events.length, stableEvents)
  assert.equal(facade.history.canUndo(), true)
  assert.equal(facade.history.canRedo(), false)

  const resourcesAfter = facade.geometry.capabilities()
  assert.deepEqual(
    { shapeCount: resourcesAfter.shapeCount, kernelReferenceCount: resourcesAfter.kernelReferenceCount, releasedShapeCount: resourcesAfter.releasedShapeCount },
    { shapeCount: resourcesBefore.shapeCount, kernelReferenceCount: resourcesBefore.kernelReferenceCount, releasedShapeCount: resourcesBefore.releasedShapeCount },
  )
})
