package controllogic

import "testing"

func TestControlLogicVersioning(t *testing.T) {
	dir := t.TempDir()
	s, err := NewStore(dir)
	if err != nil {
		t.Fatal(err)
	}

	g := Graph{ID: "cl-1", Name: "loop", Enabled: true,
		Nodes: []Node{{ID: "n1", Kind: "trigger.timer", Params: map[string]string{"interval": "1000"}}}}
	if err := s.Save(g); err != nil {
		t.Fatalf("Save v1: %v", err)
	}
	if got, _ := s.Get("cl-1"); got.Version != 1 {
		t.Fatalf("after create: version=%d", got.Version)
	}

	// Two edits → v2, v3.
	g.Name = "loop-2"
	if err := s.Save(g); err != nil {
		t.Fatalf("Save v2: %v", err)
	}
	g.Name = "loop-3"
	if err := s.Save(g); err != nil {
		t.Fatalf("Save v3: %v", err)
	}
	if got, _ := s.Get("cl-1"); got.Version != 3 || got.Name != "loop-3" {
		t.Fatalf("current: version=%d name=%q", got.Version, got.Name)
	}

	versions, err := s.Versions("cl-1")
	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, err := s.GetVersion("cl-1", 1)
	if err != nil || v1.Name != "loop" {
		t.Fatalf("GetVersion v1: name=%q err=%v", v1.Name, err)
	}

	// Promote v1 → v4.
	promoted, err := s.Promote("cl-1", 1)
	if err != nil {
		t.Fatalf("Promote: %v", err)
	}
	if promoted.Version != 4 || promoted.Name != "loop" {
		t.Errorf("promote: version=%d name=%q", promoted.Version, promoted.Name)
	}

	// Fork v3 → new id, version 1.
	forked, err := s.Fork("cl-1", 3)
	if err != nil {
		t.Fatalf("Fork: %v", err)
	}
	if forked.Version != 1 || forked.ID == "cl-1" {
		t.Errorf("fork: id=%q version=%d", forked.ID, forked.Version)
	}
	if got, err := s.Get(forked.ID); err != nil || got.Name != forked.Name {
		t.Errorf("forked graph not stored: %v", err)
	}
}
