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 { ColorValue, DocumentSnapshot, FacadeEvent } from '../src/facade/types'

const fixture = (): DocumentSnapshot => ({
  id: 'property-color-transaction',
  label: 'PropertyColor Transaction',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [
    { id: 'ColorProbe', label: 'Color probe', type: 'feature', state: 'valid' },
    { id: 'ImmutableColorProbe', label: 'Immutable color probe', type: 'feature', state: 'valid' },
  ],
  objects: [
    {
      id: 'ColorProbe',
      typeId: 'App::FeatureTest',
      properties: [{ name: 'Colour', label: 'Colour', group: 'Test', scope: 'data', type: 'App::PropertyColor', value: [0, 0, 0, 1], recompute: true }],
    },
    {
      id: 'ImmutableColorProbe',
      typeId: 'App::FeatureTest',
      properties: [{ name: 'Colour', label: 'Immutable colour', group: 'Test', scope: 'data', type: 'App::PropertyColor', value: [1, 1, 1, 0], nativeStatus: encodeFreecadPropertyStatus(['Immutable']), readOnly: true, recompute: true }],
    },
  ],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { ColorProbe: 'up-to-date', ImmutableColorProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

const valueOf = (facade: ReturnType<typeof createWebCadFacade>, objectId = 'ColorProbe') => facade.app.document.getObject(objectId)?.properties.find((property) => property.name === 'Colour')?.value

test('App::PropertyColor 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 requested: ColorValue = [0.125, 0.375, 0.625, 0.875]

  facade.app.document.setProperty({ objectId: 'ColorProbe', propertyName: 'Colour', value: requested, expectedDocumentVersion: 1 })
  requested[0] = 1
  assert.deepEqual(valueOf(facade), [0.125, 0.375, 0.625, 0.875])
  const exposed = valueOf(facade) as number[]
  exposed[1] = 1
  assert.deepEqual(valueOf(facade), [0.125, 0.375, 0.625, 0.875])
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.app.document.getActive().dirty, true)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.ColorProbe, '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.deepEqual(valueOf(facade), [0, 0, 0, 1])
  assert.equal(facade.app.document.getActive().version, 1)
  assert.equal(facade.history.canUndo(), false)
  assert.equal(facade.history.canRedo(), true)
  facade.history.redo()
  assert.deepEqual(valueOf(facade), [0.125, 0.375, 0.625, 0.875])
  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: 'ColorProbe', propertyName: 'Colour', value: [0, 0, 0, 0], expectedDocumentVersion: 1 }), /Stale document version: expected 1, current 2/)
  const cancelled = new AbortController()
  cancelled.abort()
  assert.throws(() => facade.app.document.setProperty({ objectId: 'ColorProbe', propertyName: 'Colour', value: [0, 0, 0, 0], expectedDocumentVersion: 2, signal: cancelled.signal }), (error: unknown) => error instanceof DOMException && error.name === 'AbortError')
  assert.throws(() => facade.app.document.setProperty({ objectId: 'ColorProbe', propertyName: 'Colour', value: [0, 0, 0, Number.NaN] }), /four finite RGBA channels/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'ImmutableColorProbe', propertyName: 'Colour', value: [0, 0, 0, 1] }), /Immutable colour 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()
})
