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-file-facade',
  label: 'PropertyFile Facade',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [{ id: 'FileProbe', label: 'File probe', type: 'feature', state: 'valid' }],
  objects: [{ id: 'FileProbe', typeId: 'Mesh::Import', properties: [{ name: 'FileName', label: 'File name', group: '', scope: 'data', type: 'App::PropertyFile', value: 'mesh-data/cube.stl', recompute: true }] }],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { FileProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

test('App::PropertyFile accepts only project-relative resource references through the Facade', () => {
  const facade = createWebCadFacade({ initialDocument: fixture(), initialSelectedObjectIds: ['FileProbe'], 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: 'FileProbe', propertyName: 'FileName', value: 'project-files/updated.stl' })
  assert.equal(facade.app.document.getObject('FileProbe')?.properties[0].value, 'project-files/updated.stl')
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.app.document.getActive().dirty, true)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.FileProbe, 'touched')
  assert.deepEqual(events.map((event) => event.type), ['property.before-change', 'property.changed', 'transaction.committed'])

  const stable = JSON.stringify(facade.app.document.getActive())
  for (const value of ['/home/user/model.stl', '../model.stl', 'folder/../model.stl', 'C:\\model.stl', 'https://example.test/model.stl', 'folder\\model.stl', 'folder//model.stl', `model\0.stl`]) {
    assert.throws(() => facade.app.document.setProperty({ objectId: 'FileProbe', propertyName: 'FileName', value }), /safe project-relative file reference/)
    assert.equal(JSON.stringify(facade.app.document.getActive()), stable)
  }
  assert.throws(() => facade.app.document.setProperty({ objectId: 'FileProbe', propertyName: 'FileName', value: 42 as unknown as string }), /project-relative file reference/)
})

test('App::PropertyFile uses the native String element and keeps unsafe host paths non-editable', () => {
  const document = fixture()
  const facade = createWebCadFacade({ initialDocument: document, runtimeMode: 'mock' })
  const archive = facade.project.fcstd.serializeMetadata(document)
  const documentXml = new TextDecoder().decode(unzipSync(archive)['Document.xml'])
  assert.match(documentXml, /<Object name="FileProbe" type="Mesh::Import"/)
  assert.match(documentXml, /<Property name="FileName" type="App::PropertyFile"><String value="mesh-data\/cube\.stl"\/><\/Property>/)
  const inspection = facade.project.fcstd.inspect(archive)
  const object = inspection.objects.find(({ name }) => name === 'FileProbe')
  assert.equal(object?.support, 'recognized')
  const summary = object?.properties.find(({ name }) => name === 'FileName')
  assert.deepEqual({ typeId: summary?.typeId, element: summary?.element }, { typeId: 'App::PropertyFile', element: 'String' })
  assert.deepEqual(decodeFcstdPropertyValue(summary!), { value: 'mesh-data/cube.stl', decoded: true })
  assert.equal(decodeFcstdPropertyValue({ name: 'FileName', typeId: 'App::PropertyFile', element: 'String', value: '/home/user/model.stl' }).decoded, false)
  assert.equal(decodeFcstdPropertyValue({ name: 'FileName', typeId: 'App::PropertyFile', element: 'PropertyFile', value: 'mesh-data/cube.stl' }).decoded, false)

  const rewritten = facade.project.fcstd.rewriteFile(archive, { objectName: 'FileProbe', propertyName: 'FileName', value: 'project-files/rewritten.stl', expectedValue: 'mesh-data/cube.stl' })
  const rewrittenProperty = facade.project.fcstd.inspect(rewritten).objects[0].properties.find(({ name }) => name === 'FileName')
  assert.deepEqual(decodeFcstdPropertyValue(rewrittenProperty!), { value: 'project-files/rewritten.stl', decoded: true })
  assert.match(new TextDecoder().decode(unzipSync(rewritten)['Document.xml']), /<Object(?=[^>]*name="FileProbe")(?=[^>]*type="Mesh::Import")(?=[^>]*Touched="1")[^>]*\/>/)
  assert.throws(() => facade.project.fcstd.rewriteFile(archive, { objectName: 'FileProbe', propertyName: 'FileName', value: 'project-files/rewritten.stl', expectedValue: 'mesh-data/other.stl' }), /does not match expectedValue/)
  assert.throws(() => facade.project.fcstd.rewriteFile(archive, { objectName: 'FileProbe', propertyName: 'FileName', value: '/home/user/model.stl' }), /safe project-relative file reference/)

  document.objects[0].properties[0].value = '/home/user/model.stl'
  assert.throws(() => facade.project.fcstd.serializeMetadata(document), /safe project-relative file reference/)
})
