import { createHash } from 'node:crypto'
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, IncludedFileValue } from '../src/facade/types'

const fixture = (): DocumentSnapshot => ({
  id: 'property-fileincluded-transaction',
  label: 'PropertyFileIncluded Transaction',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [
    { id: 'IncludedProbe', label: 'Included file probe', type: 'feature', state: 'valid' },
    { id: 'ImmutableIncludedProbe', label: 'Immutable included file probe', type: 'feature', state: 'valid' },
  ],
  objects: [
    {
      id: 'IncludedProbe',
      typeId: 'App::DocumentObjectFileIncluded',
      properties: [{ name: 'File', label: 'Included file', group: 'Resource', scope: 'data', type: 'App::PropertyFileIncluded', value: null, recompute: true }],
    },
    {
      id: 'ImmutableIncludedProbe',
      typeId: 'App::DocumentObjectFileIncluded',
      properties: [{ name: 'File', label: 'Immutable included file', group: 'Resource', scope: 'data', type: 'App::PropertyFileIncluded', value: null, nativeStatus: encodeFreecadPropertyStatus(['Immutable']), readOnly: true, recompute: true }],
    },
  ],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { IncludedProbe: 'up-to-date', ImmutableIncludedProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

const valueOf = (facade: ReturnType<typeof createWebCadFacade>) => facade.app.document.getObject('IncludedProbe')?.properties.find((property) => property.name === 'File')?.value as IncludedFileValue | null
const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex')

test('App::PropertyFileIncluded transaction closes undo, redo, stale, abort, 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 = new Uint8Array([0, 17, 34, 51, 255])

  const committedValue = await facade.app.document.setIncludedFile({ objectId: 'IncludedProbe', propertyName: 'File', fileName: 'payload.bin', bytes: requested, expectedDocumentVersion: 1 })
  requested[0] = 99
  assert.deepEqual(valueOf(facade), committedValue)
  assert.deepEqual([...(await facade.project.resource.get(committedValue.resourceHash))!], [0, 17, 34, 51, 255])
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.app.document.getActive().dirty, true)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.IncludedProbe, '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(valueOf(facade), null)
  assert.equal(facade.app.document.getActive().version, 1)
  assert.equal(facade.history.canUndo(), false)
  assert.equal(facade.history.canRedo(), true)
  assert.deepEqual([...(await facade.project.resource.get(committedValue.resourceHash))!], [0, 17, 34, 51, 255])
  facade.history.redo()
  assert.deepEqual(valueOf(facade), committedValue)
  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
  await assert.rejects(facade.app.document.setIncludedFile({ objectId: 'IncludedProbe', propertyName: 'File', fileName: 'stale.bin', bytes: new Uint8Array([1]), expectedDocumentVersion: 1 }), /Stale document version: expected 1, current 2/)

  const preCancelled = new AbortController()
  preCancelled.abort()
  await assert.rejects(facade.app.document.setIncludedFile({ objectId: 'IncludedProbe', propertyName: 'File', fileName: 'pre-cancelled.bin', bytes: new Uint8Array([2]), expectedDocumentVersion: 2, signal: preCancelled.signal }), (error: unknown) => error instanceof DOMException && error.name === 'AbortError')

  const cancelledBytes = new Uint8Array([3, 4, 5, 6])
  const cancelledHash = sha256(cancelledBytes)
  const cancelled = new AbortController()
  const cancelledMutation = facade.app.document.setIncludedFile({ objectId: 'IncludedProbe', propertyName: 'File', fileName: 'cancelled.bin', bytes: cancelledBytes, expectedDocumentVersion: 2, signal: cancelled.signal })
  cancelled.abort()
  await assert.rejects(cancelledMutation, (error: unknown) => error instanceof DOMException && error.name === 'AbortError')
  assert.equal(await facade.project.resource.get(cancelledHash), null)

  const invalidBytes = new Uint8Array([7, 8, 9])
  const invalidHash = sha256(invalidBytes)
  await assert.rejects(facade.app.document.setIncludedFile({ objectId: 'IncludedProbe', propertyName: 'File', fileName: 'invalid.bin', bytes: invalidBytes, mediaType: 'invalid', expectedDocumentVersion: 2 }), /simple MIME type/)
  assert.equal(await facade.project.resource.get(invalidHash), null)
  await assert.rejects(facade.app.document.setIncludedFile({ objectId: 'ImmutableIncludedProbe', propertyName: 'File', fileName: 'locked.bin', bytes: new Uint8Array([10]), expectedDocumentVersion: 2 }), /Immutable included file 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 raceLeft = new Uint8Array([11, 12, 13])
  const raceRight = new Uint8Array([14, 15, 16])
  const race = await Promise.allSettled([
    facade.app.document.setIncludedFile({ objectId: 'IncludedProbe', propertyName: 'File', fileName: 'race-left.bin', bytes: raceLeft, expectedDocumentVersion: 2 }),
    facade.app.document.setIncludedFile({ objectId: 'IncludedProbe', propertyName: 'File', fileName: 'race-right.bin', bytes: raceRight, expectedDocumentVersion: 2 }),
  ])
  assert.equal(race.filter((result) => result.status === 'fulfilled').length, 1)
  assert.equal(race.filter((result) => result.status === 'rejected').length, 1)
  const winner = race.find((result): result is PromiseFulfilledResult<IncludedFileValue> => result.status === 'fulfilled')!.value
  const loserHash = winner.resourceHash === sha256(raceLeft) ? sha256(raceRight) : sha256(raceLeft)
  assert.deepEqual(valueOf(facade), winner)
  assert.ok(await facade.project.resource.get(winner.resourceHash))
  assert.equal(await facade.project.resource.get(loserHash), null)
  assert.equal(facade.app.document.getActive().version, 3)
  assert.deepEqual(events.slice(stableEvents).map((event) => event.type), ['property.before-change', 'property.changed', 'transaction.committed'])

  facade.history.undo()
  assert.deepEqual(valueOf(facade), committedValue)
  assert.ok(await facade.project.resource.get(winner.resourceHash))
  facade.history.redo()
  assert.deepEqual(valueOf(facade), winner)

  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()
})
