import { createAssembly } from './facade/assembly'
import type { AssemblySnapshot } from './facade/assembly'

type WorkerRequest = { id: number; snapshot: AssemblySnapshot }
type WorkerResponse = { id: number; snapshot?: AssemblySnapshot; error?: string }

self.addEventListener('message', (event: MessageEvent<WorkerRequest>) => {
  const response: WorkerResponse = { id: event.data.id }
  try {
    const source = event.data.snapshot
    const assembly = createAssembly(source.id, source.label)
    for (const component of source.components) assembly.addComponent(component)
    for (const connector of source.connectors) assembly.addConnector(connector)
    for (const joint of source.joints) assembly.addJoint(joint)
    response.snapshot = assembly.solve()
  } catch (error) {
    response.error = error instanceof Error ? error.message : String(error)
  }
  self.postMessage(response)
})

export {}
