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-integerset-transaction', label: 'PropertyIntegerSet Transaction', version: 1, dirty: false, readOnly: false, units: 'mm',
  tree: [{ id: 'NodesProbe', label: 'Nodes probe', type: 'feature', state: 'valid' }],
  objects: [{ id: 'NodesProbe', typeId: 'Fem::FemSetNodesObject', properties: [{ name: 'Nodes', label: 'Nodes', group: 'Node indexes', scope: 'data', type: 'App::PropertyIntegerSet', value: [1, 3], recompute: true }] }],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { NodesProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

const valueOf = (facade: ReturnType<typeof createWebCadFacade>) => facade.app.document.getObject('NodesProbe')?.properties[0].value

test('App::PropertyIntegerSet transaction closes normalization, undo, redo, stale, cancel, failure and resources', async () => {
  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()
  const requested = [5, 2, 5]
  facade.app.document.setProperty({ objectId: 'NodesProbe', propertyName: 'Nodes', value: requested, expectedDocumentVersion: 1 })
  requested[0] = 99
  assert.deepEqual(valueOf(facade), [2, 5])
  const exposed = valueOf(facade) as number[]
  exposed[0] = 99
  assert.deepEqual(valueOf(facade), [2, 5])
  assert.equal(facade.app.document.getActive().version, 2)
  assert.deepEqual(events.map(({ type }) => type), ['property.before-change', 'property.changed', 'transaction.committed'])
  assert.equal(new Set(events.map((event) => 'transactionId' in event ? event.transactionId : '')).size, 1)
  facade.history.undo(); assert.deepEqual(valueOf(facade), [1, 3]); assert.equal(facade.history.canRedo(), true)
  facade.history.redo(); assert.deepEqual(valueOf(facade), [2, 5]); assert.equal(facade.history.canUndo(), true)

  const stable = JSON.stringify(facade.app.document.getActive())
  const eventCount = events.length
  assert.throws(() => facade.app.document.setProperty({ objectId: 'NodesProbe', propertyName: 'Nodes', value: [7], expectedDocumentVersion: 1 }), /Stale document version/)
  const cancelled = new AbortController(); cancelled.abort()
  assert.throws(() => facade.app.document.setProperty({ objectId: 'NodesProbe', propertyName: 'Nodes', value: [7], signal: cancelled.signal }), (error: unknown) => error instanceof DOMException && error.name === 'AbortError')
  assert.throws(() => facade.app.document.setProperty({ objectId: 'NodesProbe', propertyName: 'Nodes', value: [1.5] }), /safe-integer array/)
  assert.equal(JSON.stringify(facade.app.document.getActive()), stable)
  assert.equal(events.length, eventCount)
  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 })
  await facade.project.dispose()
})
