//go:build js && wasm

package main

import (
	"context"
	"encoding/json"
	"syscall/js"
	"zyel.example/workerlab/engine"
)

func main() {
	run := js.FuncOf(func(this js.Value, args []js.Value) any {
		if len(args) != 1 {
			return nil
		}
		encoded := args[0].String()
		go func() {
			config := engine.Config{}
			if err := json.Unmarshal([]byte(encoded), &config); err != nil {
				js.Global().Call("postMessage", map[string]any{"type": "error", "message": "Invalid configuration."})
				return
			}
			result, err := engine.Run(context.Background(), config)
			if err != nil {
				js.Global().Call("postMessage", map[string]any{"type": "error", "message": err.Error()})
				return
			}
			body, _ := json.Marshal(result)
			js.Global().Call("postMessage", map[string]any{"type": "result", "json": string(body)})
		}()
		return nil
	})
	js.Global().Set("runWorkerLab", run)
	js.Global().Call("postMessage", map[string]any{"type": "ready"})
	select {}
}
