package store

import "testing"

func TestSetWorkloadGitOps_RoundTrip(t *testing.T) {
	s := newTestStore(t)
	w, err := s.CreateWorkload(Workload{Kind: "plugin", Name: "app", SourceKind: "dockerfile"})
	if err != nil {
		t.Fatalf("CreateWorkload: %v", err)
	}

	// Fresh row defaults: GitOps off, default path applied by CreateWorkload.
	if w.GitOpsEnabled {
		t.Fatalf("new workload should default to gitops disabled")
	}
	if w.GitOpsPath != ".tinyforge.yml" {
		t.Fatalf("default path = %q, want .tinyforge.yml", w.GitOpsPath)
	}

	// Enable with a custom path.
	if err := s.SetWorkloadGitOps(w.ID, true, "deploy/.tinyforge.yml"); err != nil {
		t.Fatalf("SetWorkloadGitOps: %v", err)
	}
	got, err := s.GetWorkloadByID(w.ID)
	if err != nil {
		t.Fatalf("GetWorkloadByID: %v", err)
	}
	if !got.GitOpsEnabled || got.GitOpsPath != "deploy/.tinyforge.yml" {
		t.Fatalf("after enable: enabled=%v path=%q", got.GitOpsEnabled, got.GitOpsPath)
	}

	// Empty path falls back to the default.
	if err := s.SetWorkloadGitOps(w.ID, false, ""); err != nil {
		t.Fatalf("SetWorkloadGitOps disable: %v", err)
	}
	got, _ = s.GetWorkloadByID(w.ID)
	if got.GitOpsEnabled || got.GitOpsPath != ".tinyforge.yml" {
		t.Fatalf("after disable: enabled=%v path=%q", got.GitOpsEnabled, got.GitOpsPath)
	}
}

func TestRecordGitOpsSync(t *testing.T) {
	s := newTestStore(t)
	w, _ := s.CreateWorkload(Workload{Kind: "plugin", Name: "app", SourceKind: "static"})

	if err := s.RecordGitOpsSync(w.ID, "abc123", "2026-06-21 10:00:00"); err != nil {
		t.Fatalf("RecordGitOpsSync: %v", err)
	}
	got, _ := s.GetWorkloadByID(w.ID)
	if got.GitOpsCommitSHA != "abc123" || got.GitOpsLastSyncAt != "2026-06-21 10:00:00" {
		t.Fatalf("sync not recorded: sha=%q at=%q", got.GitOpsCommitSHA, got.GitOpsLastSyncAt)
	}
}

func TestGitOpsSetters_NotFound(t *testing.T) {
	s := newTestStore(t)
	if err := s.SetWorkloadGitOps("nope", true, ""); err == nil {
		t.Fatalf("expected ErrNotFound for missing workload")
	}
	if err := s.RecordGitOpsSync("nope", "x", "y"); err == nil {
		t.Fatalf("expected ErrNotFound for missing workload")
	}
}
