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

const fixture = (): DocumentSnapshot => ({
  id: 'property-force-transaction', label: 'PropertyForce Transaction', version: 1, dirty: false, readOnly: false, units: 'mm',
  tree: [{ id: 'ForceProbe', label: 'Force probe', type: 'feature', state: 'valid' }, { id: 'OutputForceProbe', label: 'Output force probe', type: 'feature', state: 'valid' }],
  objects: [
    { id: 'ForceProbe', typeId: 'Fem::ConstraintForce', properties: [{ name: 'Force', label: 'Force', group: '', scope: 'data', type: 'App::PropertyForce', value: 0, unit: 'mm*kg/s^2', recompute: true }] },
    { id: 'OutputForceProbe', typeId: 'Fem::ConstraintRigidBody', properties: [{ name: 'ForceX', label: 'Force X', group: 'ConstraintRigidBody', scope: 'data', type: 'App::PropertyForce', value: 0, unit: 'mm*kg/s^2', nativeStatus: encodeFreecadPropertyStatus(['PropOutput']), recompute: true }] },
  ],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { ForceProbe: 'up-to-date', OutputForceProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

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

test('App::PropertyForce transaction closes undo, redo, abort, stale, failure and resource ownership', 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()
  facade.app.document.setProperty({ objectId: 'ForceProbe', propertyName: 'Force', value: 500000, expectedDocumentVersion: 1 })
  assert.equal(force(facade), 500000)
  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.equal(force(facade), 0)
  assert.equal(facade.history.canRedo(), true)
  facade.history.redo()
  assert.equal(force(facade), 500000)
  assert.equal(facade.history.canUndo(), true)

  facade.app.document.setProperty({ objectId: 'OutputForceProbe', propertyName: 'ForceX', value: 1000, expectedDocumentVersion: 2 })
  assert.equal(facade.app.document.getObject('OutputForceProbe')?.properties[0].value, 1000)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.OutputForceProbe, 'up-to-date')

  const stable = JSON.stringify(facade.app.document.getActive())
  const eventCount = events.length
  assert.throws(() => facade.app.document.setProperty({ objectId: 'ForceProbe', propertyName: 'Force', value: 250000, expectedDocumentVersion: 1 }), /Stale document version/)
  const cancelled = new AbortController(); cancelled.abort()
  assert.throws(() => facade.app.document.setProperty({ objectId: 'ForceProbe', propertyName: 'Force', value: 250000, signal: cancelled.signal }), (error: unknown) => error instanceof DOMException && error.name === 'AbortError')
  assert.throws(() => facade.app.document.setProperty({ objectId: 'ForceProbe', propertyName: 'Force', value: 'invalid' as unknown as number }), /finite numeric value/)
  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()
})
