import assert from 'node:assert/strict'
import test from 'node:test'
import { createTechDrawPage } from '../src/facade/techDraw'
import type { TopoRefValue } from '../src/facade/types'

const ref = (id: string, version: number): TopoRefValue => ({ schemaVersion: 1, objectId: 'box', kind: 'vertex', persistentId: id, topologyVersion: version, generation: version, status: 'stable', signature: id })
const source = (revision: number) => ({ id: 'box', revision, points: [{ id: 'a', ref: ref('Vertex1', revision), point: { x: 0, y: 0, z: 0 } }, { id: 'b', ref: ref('Vertex2', revision), point: { x: 4, y: 0, z: 0 } }, { id: 'c', ref: ref('Vertex3', revision), point: { x: 4, y: 3, z: 0 } }], edges: [{ id: 'edge', start: 'a', end: 'b' }, { id: 'edge2', start: 'b', end: 'c' }] })

test('TechDraw projects stable TopoRefs and updates dimensions on source revision', () => {
  const page = createTechDrawPage()
  page.addSource(source(1))
  page.addView({ id: 'front', sourceId: 'box', direction: { x: 0, y: 0, z: 1 }, position: { x: 80, y: 80 } })
  page.addView({ id: 'section', sourceId: 'box', kind: 'section', direction: { x: 0, y: 0, z: 1 }, position: { x: 160, y: 80 }, section: { normal: { x: 1, y: 0, z: 0 }, offset: 2 } })
  const dimension = page.addDimension({ id: 'length', sourceId: 'box', first: ref('Vertex1', 1), second: ref('Vertex2', 1), label: 'Length' })
  page.addAnnotation({ id: 'note', text: 'Box', position: { x: 20, y: 20 }, style: 'callout' })
  page.addGeometricTolerance({ id: 'flatness', sourceId: 'box', reference: ref('Vertex3', 1), characteristic: 'flatness', value: 0.05, datum: 'A' })
  assert.equal(dimension.value, 4)
  page.updateSource({ ...source(2), points: source(2).points.map((point) => point.id === 'b' ? { ...point, point: { x: 6, y: 0, z: 0 } } : point) })
  assert.equal(page.snapshot().dimensions[0].value, 6)
  assert.equal(page.snapshot().views[0].sourceRevision, 2)
  assert.match(page.exportSvg(), /data-view="section"/)
  assert.match(page.exportSvg(), /data-tolerance="flatness"/)
  assert.match(new TextDecoder().decode(page.exportPdf()), /^%PDF-1\.4[\s\S]+xref[\s\S]+%%EOF\n$/)
})

test('TechDraw marks deleted TopoRefs unresolved and rejects invalid input', () => {
  const page = createTechDrawPage()
  page.addSource(source(1))
  page.addDimension({ id: 'missing', sourceId: 'box', first: ref('Vertex1', 1), second: ref('Missing', 1) })
  page.addGeometricTolerance({ id: 'position', sourceId: 'box', reference: ref('Missing', 1), characteristic: 'position', value: 0.1 })
  assert.equal(page.snapshot().dimensions[0].status, 'unresolved')
  assert.equal(page.snapshot().tolerances[0].status, 'unresolved')
  assert.throws(() => page.addView({ id: 'bad', sourceId: 'box', direction: { x: 0, y: 0, z: 0 }, position: { x: 0, y: 0 } }), /non-zero/)
  assert.throws(() => page.addSource(source(1)), /already exists/)
})
