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-heatflux-transaction', label: 'PropertyHeatFlux Transaction', version: 1, dirty: false, readOnly: false, units: 'mm',
  tree: [{ id: 'HeatFluxProbe', label: 'Heat flux probe', type: 'feature', state: 'valid' }],
  objects: [{ id: 'HeatFluxProbe', typeId: 'Fem::ConstraintHeatflux', properties: [{ name: 'DFlux', label: 'DFlux', group: 'ConstraintHeatflux', scope: 'data', type: 'App::PropertyHeatFlux', value: 0, unit: 'kg/s^3', recompute: true }] }],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { HeatFluxProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

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

test('App::PropertyHeatFlux 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: 'HeatFluxProbe', propertyName: 'DFlux', value: 500, expectedDocumentVersion: 1 })
  assert.equal(heatFlux(facade), 500)
  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(heatFlux(facade), 0)
  assert.equal(facade.history.canRedo(), true)
  facade.history.redo()
  assert.equal(heatFlux(facade), 500)
  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: 'HeatFluxProbe', propertyName: 'DFlux', value: 250, expectedDocumentVersion: 1 }), /Stale document version/)
  const cancelled = new AbortController(); cancelled.abort()
  assert.throws(() => facade.app.document.setProperty({ objectId: 'HeatFluxProbe', propertyName: 'DFlux', value: 250, signal: cancelled.signal }), (error: unknown) => error instanceof DOMException && error.name === 'AbortError')
  assert.throws(() => facade.app.document.setProperty({ objectId: 'HeatFluxProbe', propertyName: 'DFlux', 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()
})
