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-font-transaction',
  label: 'PropertyFont Transaction',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [
    { id: 'FontProbe', label: 'Font probe', type: 'feature', state: 'valid' },
    { id: 'ImmutableFontProbe', label: 'Immutable font probe', type: 'feature', state: 'valid' },
  ],
  objects: [
    { id: 'FontProbe', typeId: 'TechDraw::DrawViewAnnotation', properties: [{ name: 'Font', label: 'Font', group: 'Annotation', scope: 'data', type: 'App::PropertyFont', value: 'osifont', recompute: true }] },
    { id: 'ImmutableFontProbe', typeId: 'TechDraw::DrawViewAnnotation', properties: [{ name: 'Font', label: 'Immutable font', group: 'Annotation', scope: 'data', type: 'App::PropertyFont', value: 'osifont', nativeStatus: encodeFreecadPropertyStatus(['Immutable']), readOnly: true, recompute: true }] },
  ],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { FontProbe: 'up-to-date', ImmutableFontProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

const valueOf = (facade: ReturnType<typeof createWebCadFacade>, objectId = 'FontProbe') => facade.app.document.getObject(objectId)?.properties.find(({ name }) => name === 'Font')?.value

test('App::PropertyFont 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()
  facade.app.document.setProperty({ objectId: 'FontProbe', propertyName: 'Font', value: 'DejaVu Sans', expectedDocumentVersion: 1 })
  assert.equal(valueOf(facade), 'DejaVu Sans')
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.app.document.getActive().dirty, true)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.FontProbe, 'touched')
  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(valueOf(facade), 'osifont')
  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(valueOf(facade), 'DejaVu Sans')
  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: 'FontProbe', propertyName: 'Font', value: 'Stale Font', expectedDocumentVersion: 1 }), /Stale document version: expected 1, current 2/)
  const cancelled = new AbortController()
  cancelled.abort()
  assert.throws(() => facade.app.document.setProperty({ objectId: 'FontProbe', propertyName: 'Font', value: 'Cancelled Font', expectedDocumentVersion: 2, signal: cancelled.signal }), (error: unknown) => error instanceof DOMException && error.name === 'AbortError')
  assert.throws(() => facade.app.document.setProperty({ objectId: 'FontProbe', propertyName: 'Font', value: 42 as unknown as string }), /requires a string value/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'FontProbe', propertyName: 'Font', value: `Bad\0Font` }), /unsupported control characters/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'ImmutableFontProbe', propertyName: 'Font', value: 'Unlocked Font' }), /Immutable font 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()
})
