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 faceEntry = (persistentId: string, area: number, index: number) => ({
  ref: { shapeId: 'AreaBox-shape', kind: 'face' as const, persistentId, topologyVersion: 1, status: 'stable' as const },
  signature: { kind: 'face' as const, canonical: persistentId, hash: persistentId, centroid: [index, 0, 0] as [number, number, number], bounds: { min: [index, 0, 0] as [number, number, number], max: [index + 1, 1, 0] as [number, number, number] }, area, normal: [0, 0, 1] as [number, number, number] },
})

const fixture = (): DocumentSnapshot => ({
  id: 'property-area-transaction',
  label: 'PropertyArea Transaction',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [{ id: 'AreaBox', label: 'Area box', type: 'feature', state: 'valid' }, { id: 'AreaProbe', label: 'Area probe', type: 'feature', state: 'valid' }],
  objects: [
    {
      id: 'AreaBox',
      typeId: 'Part::Box',
      properties: [],
      topology: {
        shapeId: 'AreaBox-shape', documentVersion: 1, generation: 1,
        entries: [faceEntry('box-face-1', 10, 0), faceEntry('box-face-2', 10, 1)],
        migration: { previousGeneration: null, matches: [] },
        history: { operationId: 'AreaBox:1', provider: 'occt-native', relations: [], counts: { preserved: 0, modified: 0, generated: 0, deleted: 0, ambiguous: 0 } },
      },
    },
    {
      id: 'AreaProbe',
      typeId: 'Measure::MeasureArea',
      properties: [
        { name: 'Area', label: 'Area', group: 'Measurement', scope: 'data', type: 'App::PropertyArea', value: 10, unit: 'mm^2', nativeStatus: encodeFreecadPropertyStatus(['PropReadOnly', 'PropOutput']), readOnly: true, recompute: false },
        { name: 'Elements', label: 'Elements', group: 'Measurement', scope: 'data', type: 'App::PropertyLinkSubList', value: { schemaVersion: 1, entries: [{ objectId: 'AreaBox', subElement: 'Face1' }] }, recompute: true },
      ],
    },
  ],
  dependencies: [{ sourceId: 'AreaProbe', targetId: 'AreaBox', relation: 'link', propertyName: 'Elements', reference: 'Elements[0]' }],
  recompute: { generation: 0, status: 'idle', objectStates: { AreaBox: 'up-to-date', AreaProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

const propertyValue = (facade: ReturnType<typeof createWebCadFacade>, name: 'Area' | 'Elements') => facade.app.document.getObject('AreaProbe')?.properties.find((property) => property.name === name)?.value

test('App::PropertyArea transaction closes undo, redo, stale, cancel, 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()
  const editedElements = { schemaVersion: 1 as const, entries: [{ objectId: 'AreaBox', subElement: 'Face1' }, { objectId: 'AreaBox', subElement: 'Face2' }] }

  facade.app.document.setProperty({ objectId: 'AreaProbe', propertyName: 'Elements', value: editedElements, expectedDocumentVersion: 1 })
  assert.equal(propertyValue(facade, 'Area'), 20)
  assert.deepEqual(propertyValue(facade, 'Elements'), editedElements)
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.app.document.getActive().dirty, true)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.AreaProbe, 'touched')
  assert.deepEqual(events.map((event) => event.type), ['property.before-change', 'property.changed', 'transaction.committed'])
  assert.equal(new Set(events.map((event) => 'transactionId' in event ? event.transactionId : '')).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(propertyValue(facade, 'Area'), 10)
  assert.deepEqual(propertyValue(facade, 'Elements'), { schemaVersion: 1, entries: [{ objectId: 'AreaBox', subElement: 'Face1' }] })
  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(propertyValue(facade, 'Area'), 20)
  assert.deepEqual(propertyValue(facade, 'Elements'), editedElements)
  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: 'AreaProbe', propertyName: 'Elements', value: { schemaVersion: 1, entries: [] }, expectedDocumentVersion: 1 }), /Stale document version: expected 1, current 2/)
  const cancelled = new AbortController()
  cancelled.abort()
  assert.throws(() => facade.app.document.setProperty({ objectId: 'AreaProbe', propertyName: 'Elements', value: { schemaVersion: 1, entries: [] }, expectedDocumentVersion: 2, signal: cancelled.signal }), (error: unknown) => error instanceof DOMException && error.name === 'AbortError')
  assert.throws(() => facade.app.document.setProperty({ objectId: 'AreaProbe', propertyName: 'Elements', value: { schemaVersion: 1, entries: [{ objectId: 'AreaBox', subElement: 'Edge1' }] }, expectedDocumentVersion: 2 }), /Cannot calculate area/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'AreaProbe', propertyName: 'Area', value: 30, expectedDocumentVersion: 2 }), /Area is read-only/)
  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 },
  )
  await facade.project.dispose()
})
