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 { convertQuantity, quantityFromUnit } from '../src/facade/units'
import type { DocumentSnapshot } from '../src/facade/types'

const fixture = (): DocumentSnapshot => ({
  id: 'property-force-facade',
  label: 'PropertyForce Facade',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [
    { id: 'ForceProbe', label: 'Force probe', type: 'feature', state: 'valid' },
    { id: 'RigidForceProbe', label: 'Rigid force probe', type: 'feature', state: 'valid' },
  ],
  objects: [
    { id: 'ForceProbe', typeId: 'Fem::ConstraintForce', properties: [{ name: 'Force', label: 'Force', group: '', scope: 'data', type: 'App::PropertyForce', value: 0, unit: 'mm*kg/s^2', recompute: true }] },
    { id: 'RigidForceProbe', typeId: 'Fem::ConstraintRigidBody', properties: [{ name: 'ForceX', label: 'Force X', group: 'ConstraintRigidBody', scope: 'data', type: 'App::PropertyForce', value: 0, unit: 'mm*kg/s^2', nativeStatus: encodeFreecadPropertyStatus(['PropOutput']), recompute: true }] },
  ],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { ForceProbe: 'up-to-date', RigidForceProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

test('App::PropertyForce uses the native internal unit and Float FCStd codec', () => {
  const facade = createWebCadFacade({ initialDocument: fixture(), initialSelectedObjectIds: ['ForceProbe'], runtimeMode: 'mock' })
  facade.app.document.setProperty({ objectId: 'ForceProbe', propertyName: 'Force', value: 500000 })
  const edited = facade.app.document.getActive()
  const property = edited.objects[0].properties[0]
  assert.deepEqual({ type: property.type, value: property.value, unit: property.unit }, { type: 'App::PropertyForce', value: 500000, unit: 'mm*kg/s^2' })
  assert.equal(edited.version, 2)
  assert.equal(edited.dirty, true)
  assert.equal(edited.recompute?.objectStates.ForceProbe, 'touched')
  assert.throws(() => facade.app.document.setProperty({ objectId: 'ForceProbe', propertyName: 'Force', value: '500 N' as unknown as number }), /finite numeric value/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'ForceProbe', propertyName: 'Force', value: Number.POSITIVE_INFINITY }), /finite numeric value/)
  facade.app.document.setProperty({ objectId: 'RigidForceProbe', propertyName: 'ForceX', value: 1000 })
  assert.equal(facade.app.document.getObject('RigidForceProbe')?.properties[0].value, 1000)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.RigidForceProbe, 'up-to-date')

  const archive = facade.project.fcstd.serializeMetadata(edited)
  const documentXml = new TextDecoder().decode(unzipSync(archive)['Document.xml'])
  assert.match(documentXml, /<Property name="Force" type="App::PropertyForce"><Float value="500000"\/><\/Property>/)
  assert.doesNotMatch(documentXml, /<Property name="Force"[^>]+group=/)
  const summary = facade.project.fcstd.inspect(archive).objects.find(({ name }) => name === 'ForceProbe')?.properties.find(({ name }) => name === 'Force')
  assert.deepEqual({ typeId: summary?.typeId, element: summary?.element }, { typeId: 'App::PropertyForce', element: 'Float' })
  assert.deepEqual(decodeFcstdPropertyValue(summary!), { value: 500000, decoded: true })

  const rewritten = facade.project.fcstd.rewriteNumeric(archive, { objectName: 'ForceProbe', propertyName: 'Force', typeId: 'App::PropertyForce', value: -5000, expectedValue: 500000 })
  const rewrittenSummary = facade.project.fcstd.inspect(rewritten).objects.find(({ name }) => name === 'ForceProbe')?.properties.find(({ name }) => name === 'Force')
  assert.deepEqual(decodeFcstdPropertyValue(rewrittenSummary!), { value: -5000, decoded: true })
  assert.throws(() => facade.project.fcstd.rewriteNumeric(archive, { objectName: 'ForceProbe', propertyName: 'Force', typeId: 'App::PropertyForce', value: 1000, expectedValue: 1 }), /expected 1, found 500000/)
  assert.equal(convertQuantity(quantityFromUnit(2, 'kN'), 'N'), 2000)
  assert.equal(convertQuantity(quantityFromUnit(1, 'N'), 'mm*kg/s^2'), 1000)
  facade.app.document.setExpression({ objectId: 'ForceProbe', propertyName: 'Force', expression: '2 N' })
  assert.equal(facade.app.document.getObject('ForceProbe')?.properties[0].value, 2000)
  assert.equal(facade.app.document.getObject('ForceProbe')?.properties[0].expression, '2 N')
})
