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

const visibilityStatus = encodeFreecadPropertyStatus(['Immutable', 'Hidden', 'LockDynamic'])

const fixture = (): DocumentSnapshot => ({
  id: 'property-boollist-facade',
  label: 'PropertyBoolList Facade',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [
    { id: 'BoolListProbe', label: 'Bool list probe', type: 'feature', state: 'valid' },
    { id: 'VisibilityProbe', label: 'Visibility probe', type: 'feature', state: 'valid' },
  ],
  objects: [
    {
      id: 'BoolListProbe',
      typeId: 'App::FeatureTest',
      properties: [{ name: 'BoolList', label: 'Bool list', group: 'Test', scope: 'data', type: 'App::PropertyBoolList', value: [false], recompute: true }],
    },
    {
      id: 'VisibilityProbe',
      typeId: 'App::Link',
      properties: [{ name: 'VisibilityList', label: 'Visibility list', group: 'Link', scope: 'data', type: 'App::PropertyBoolList', value: [true, true], nativeStatus: visibilityStatus, hidden: true, readOnly: true, recompute: true }],
    },
  ],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { BoolListProbe: 'up-to-date', VisibilityProbe: '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::PropertyBoolList uses typed boolean values and the native BoolList bitset codec', () => {
  const facade = createWebCadFacade({ initialDocument: fixture(), initialSelectedObjectIds: ['BoolListProbe'], 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: 'BoolListProbe', propertyName: 'BoolList', value: [true, false, true] })
  assert.deepEqual(valueOf(facade, 'BoolListProbe', 'BoolList'), [true, false, true])
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.BoolListProbe, 'touched')
  assert.deepEqual(events.map((event) => event.type), ['property.before-change', 'property.changed', 'transaction.committed'])

  assert.throws(() => facade.app.document.setProperty({ objectId: 'BoolListProbe', propertyName: 'BoolList', value: [true, 1 as unknown as boolean] }), /boolean list/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'BoolListProbe', propertyName: 'BoolList', value: '101' }), /boolean list/)
  assert.deepEqual(valueOf(facade, 'BoolListProbe', 'BoolList'), [true, false, true])

  assert.throws(() => facade.app.document.setProperty({ objectId: 'VisibilityProbe', propertyName: 'VisibilityList', value: [false, true] }), /Visibility list is read-only/)
  assert.deepEqual(valueOf(facade, 'VisibilityProbe', 'VisibilityList'), [true, true])

  const archive = facade.project.fcstd.serializeMetadata(facade.app.document.getActive())
  const documentXml = new TextDecoder().decode(unzipSync(archive)['Document.xml'])
  assert.match(documentXml, /<Object name="BoolListProbe" type="App::FeatureTest"/)
  assert.match(documentXml, /<Property name="BoolList" type="App::PropertyBoolList"><BoolList value="101"\/><\/Property>/)
  assert.match(documentXml, /<Property name="VisibilityList" type="App::PropertyBoolList" status="266"><BoolList value="11"\/><\/Property>/)
  assert.doesNotMatch(documentXml, /<Property name="(?:BoolList|VisibilityList)"[^>]+group=/)

  const inspection = facade.project.fcstd.inspect(archive)
  const object = inspection.objects.find((candidate) => candidate.name === 'BoolListProbe')
  assert.equal(object?.support, 'recognized')
  const summary = object?.properties.find((property) => property.name === 'BoolList')
  assert.deepEqual({ typeId: summary?.typeId, element: summary?.element }, { typeId: 'App::PropertyBoolList', element: 'BoolList' })
  assert.deepEqual(decodeFcstdPropertyValue(summary!), { value: [true, false, true], decoded: true })
})
