import test from 'node:test'
import assert from 'node:assert/strict'
import { createMeshDocument } from '../src/facade/mesh'

test('mesh weld, quality analysis, transform and deterministic OBJ export', () => {
  const mesh = createMeshDocument('triangle', 'Triangle', { positions: [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0], indices: [0, 1, 2, 0, 3, 1] })
  assert.equal(mesh.analyze().triangles, 2)
  mesh.weldVertices()
  assert.equal(mesh.analyze().vertices, 3)
  assert.equal(mesh.analyze().boundaryEdges, 3)
  assert.equal(mesh.analyze().selfIntersections, 0)
  mesh.removeDegenerate()
  mesh.transform({ translation: [1, 2, 3], scale: 2 })
  assert.equal(mesh.analyze().bounds.min[0], 1)
  assert.match(mesh.exportObj(), /v 1\.000000 2\.000000 3\.000000/)
  assert.equal(mesh.exportObj(), mesh.exportObj())
  assert.match(mesh.exportPly(), /^ply/m)
  assert.match(mesh.exportStl(), /^solid bitbybit/m)
  assert.equal(mesh.lod(1).triangles, 1)
})

test('mesh detects crossing triangles without shared vertices', () => {
  const mesh = createMeshDocument('cross', 'Cross', { positions: [-1, -1, 0, 1, 1, 0, -1, 1, 0, -1, 1, 0, 1, -1, 0, 1, 1, 0], indices: [0, 1, 2, 3, 4, 5] })
  assert.equal(mesh.detectSelfIntersections(), 1)
  assert.equal(mesh.analyze().selfIntersections, 1)
})

test('mesh repair rejects non-boundary edges and accepts a minimal triangle hole fill', () => {
  const mesh = createMeshDocument('hole', 'Hole', { positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [] })
  mesh.fillBoundaryTriangle([0, 1], 2)
  assert.equal(mesh.analyze().triangles, 1)
  assert.throws(() => mesh.fillBoundaryTriangle([0, 1], 2), /not available/)
})
