import { test } from 'node:test'
import assert from 'node:assert/strict'
import { unzipSync } from 'fflate'
import { createWebCadFacade } from '../src/facade/mockFacade'
import { decodeFcstdPropertyValue } from '../src/facade/fcstd'
import type { DocumentSnapshot, FacadeEvent } from '../src/facade/types'

const fixture = (): DocumentSnapshot => ({
  id: 'property-integerset-facade', label: 'PropertyIntegerSet Facade', version: 1, dirty: false, readOnly: false, units: 'mm',
  tree: [{ id: 'NodesProbe', label: 'Nodes probe', type: 'feature', state: 'valid' }, { id: 'ElementsProbe', label: 'Elements probe', type: 'feature', state: 'valid' }],
  objects: [
    { id: 'NodesProbe', typeId: 'Fem::FemSetNodesObject', properties: [{ name: 'Nodes', label: 'Nodes', group: 'Node indexes', scope: 'data', type: 'App::PropertyIntegerSet', value: [], recompute: true }] },
    { id: 'ElementsProbe', typeId: 'Fem::FemSetElementNodesObject', properties: [{ name: 'Elements', label: 'Elements', group: 'Element indexes', scope: 'data', type: 'App::PropertyIntegerSet', value: [4, 10], recompute: true }] },
  ],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { NodesProbe: 'up-to-date', ElementsProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

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

test('App::PropertyIntegerSet normalizes unique integers and uses the native IntegerSet codec', () => {
  const facade = createWebCadFacade({ initialDocument: fixture(), initialSelectedObjectIds: ['NodesProbe'], 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) })
  facade.app.document.setProperty({ objectId: 'NodesProbe', propertyName: 'Nodes', value: [3, 1, 3, 2] })
  assert.deepEqual(valueOf(facade, 'NodesProbe', 'Nodes'), [1, 2, 3])
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.NodesProbe, 'touched')
  assert.deepEqual(events.map((event) => event.type), ['property.before-change', 'property.changed', 'transaction.committed'])
  assert.throws(() => facade.app.document.setProperty({ objectId: 'NodesProbe', propertyName: 'Nodes', value: [1, 1.5] }), /safe-integer array/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'NodesProbe', propertyName: 'Nodes', value: ['1'] as unknown as number[] }), /safe-integer array/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'NodesProbe', propertyName: 'Nodes', value: [Number.MAX_SAFE_INTEGER + 1] }), /safe-integer array/)
  assert.deepEqual(valueOf(facade, 'NodesProbe', 'Nodes'), [1, 2, 3])

  const archive = facade.project.fcstd.serializeMetadata(facade.app.document.getActive())
  const xml = new TextDecoder().decode(unzipSync(archive)['Document.xml'])
  assert.match(xml, /<Property name="Nodes" type="App::PropertyIntegerSet" group="Node indexes"[^>]*><IntegerSet count="3"><I v="1"\/><I v="2"\/><I v="3"\/><\/IntegerSet><\/Property>/)
  const summary = facade.project.fcstd.inspect(archive).objects.find(({ name }) => name === 'NodesProbe')?.properties.find(({ name }) => name === 'Nodes')
  assert.deepEqual({ typeId: summary?.typeId, element: summary?.element }, { typeId: 'App::PropertyIntegerSet', element: 'IntegerSet' })
  assert.deepEqual(decodeFcstdPropertyValue(summary!), { value: [1, 2, 3], decoded: true })

  const rewritten = facade.project.fcstd.rewriteIntegerSet(archive, { objectName: 'NodesProbe', propertyName: 'Nodes', value: [8, -1, 8], expectedValue: [1, 2, 3] })
  const rewrittenSummary = facade.project.fcstd.inspect(rewritten).objects.find(({ name }) => name === 'NodesProbe')?.properties.find(({ name }) => name === 'Nodes')
  assert.deepEqual(decodeFcstdPropertyValue(rewrittenSummary!), { value: [-1, 8], decoded: true })
  assert.throws(() => facade.project.fcstd.rewriteIntegerSet(archive, { objectName: 'NodesProbe', propertyName: 'Nodes', value: [4], expectedValue: [9] }), /does not match expectedValue/)
})

