package synthetic

import (
	"context"
	"testing"
)

func TestSyntheticVersioning(t *testing.T) {
	syn, _, cancel := newTestSynthetic(t)
	defer cancel()
	if err := syn.Connect(context.Background()); err != nil {
		t.Fatal(err)
	}

	// defWithGain builds a fresh def each time, mirroring how the REST handler
	// decodes a new SignalDef per request (no aliasing of slices/maps).
	defWithGain := func(g float64) SignalDef {
		return SignalDef{Name: "wf", DS: "stub", Signal: "sine_1hz",
			Pipeline: []NodeDef{{Type: "gain", Params: map[string]any{"gain": g}}}}
	}

	if err := syn.AddSignal(defWithGain(1.0)); err != nil {
		t.Fatalf("AddSignal: %v", err)
	}

	cur, err := syn.GetSignal("wf")
	if err != nil || cur.Version != 1 {
		t.Fatalf("after add: version=%d err=%v", cur.Version, err)
	}

	// Two edits → v2, v3.
	if err := syn.UpdateSignal(defWithGain(2.0)); err != nil {
		t.Fatalf("UpdateSignal: %v", err)
	}
	if err := syn.UpdateSignal(defWithGain(3.0)); err != nil {
		t.Fatalf("UpdateSignal: %v", err)
	}

	cur, _ = syn.GetSignal("wf")
	if cur.Version != 3 {
		t.Fatalf("want current v3, got v%d", cur.Version)
	}

	versions, err := syn.Versions("wf")
	if err != nil {
		t.Fatalf("Versions: %v", err)
	}
	if len(versions) != 3 {
		t.Fatalf("want 3 versions, got %d", len(versions))
	}
	if !versions[0].Current || versions[0].Version != 3 {
		t.Errorf("newest should be current v3: %+v", versions[0])
	}

	// v1 backup retrievable with original gain.
	v1, err := syn.GetVersion("wf", 1)
	if err != nil {
		t.Fatalf("GetVersion v1: %v", err)
	}
	if v1.Pipeline[0].Params["gain"] != 1.0 {
		t.Errorf("v1 gain: want 1.0, got %v", v1.Pipeline[0].Params["gain"])
	}

	// Promote v1 → becomes v4 (non-destructive).
	promoted, err := syn.PromoteVersion("wf", 1)
	if err != nil {
		t.Fatalf("Promote: %v", err)
	}
	if promoted.Version != 4 || promoted.Pipeline[0].Params["gain"] != 1.0 {
		t.Errorf("promote: version=%d gain=%v", promoted.Version, promoted.Pipeline[0].Params["gain"])
	}

	// Fork v3 → fresh signal, version 1.
	forked, err := syn.ForkVersion("wf", 3)
	if err != nil {
		t.Fatalf("Fork: %v", err)
	}
	if forked.Version != 1 || forked.Name == "wf" {
		t.Errorf("fork: name=%q version=%d", forked.Name, forked.Version)
	}
	if forked.Pipeline[0].Params["gain"] != 3.0 {
		t.Errorf("fork gain: want 3.0, got %v", forked.Pipeline[0].Params["gain"])
	}
	if _, err := syn.GetSignal(forked.Name); err != nil {
		t.Errorf("forked signal not registered: %v", err)
	}
}
