package store

import (
	"io"
	"log"
	"path/filepath"
	"testing"
)

// SaveCustomerConfig bumps config_version on every save: a new row seeds at 1, each subsequent save
// increments. This counter is the signal the controller's pull-based config-refresh keys off.
func TestSaveCustomerConfig_BumpsConfigVersion(t *testing.T) {
	s, err := New(filepath.Join(t.TempDir(), "cv.db"), log.New(io.Discard, "", 0))
	if err != nil {
		t.Fatalf("store.New: %v", err)
	}
	t.Cleanup(func() { s.Close() })

	save := func(json string) {
		t.Helper()
		if err := s.SaveCustomerConfig(&CustomerConfig{
			CustomerID: "c", RetrievalPassword: "pw", APIKey: "k", ConfigJSON: json,
		}); err != nil {
			t.Fatalf("SaveCustomerConfig: %v", err)
		}
	}
	get := func() int {
		t.Helper()
		cfg, err := s.GetCustomerConfig("c")
		if err != nil || cfg == nil {
			t.Fatalf("GetCustomerConfig: %v (cfg=%v)", err, cfg)
		}
		return cfg.ConfigVersion
	}

	save("{}")
	if v := get(); v != 1 {
		t.Fatalf("after create config_version = %d, want 1", v)
	}
	save(`{"git":{"username":"a"}}`)
	if v := get(); v != 2 {
		t.Fatalf("after first edit config_version = %d, want 2", v)
	}
	save(`{"git":{"username":"b"}}`)
	if v := get(); v != 3 {
		t.Fatalf("after second edit config_version = %d, want 3", v)
	}

	// A second, independent customer starts its own counter at 1 (not affected by c's bumps).
	if err := s.SaveCustomerConfig(&CustomerConfig{
		CustomerID: "d", RetrievalPassword: "pw", APIKey: "k2", ConfigJSON: "{}",
	}); err != nil {
		t.Fatalf("SaveCustomerConfig(d): %v", err)
	}
	cfgD, _ := s.GetCustomerConfig("d")
	if cfgD.ConfigVersion != 1 {
		t.Errorf("new customer d config_version = %d, want 1 (per-customer counter)", cfgD.ConfigVersion)
	}
}
