package platform

import (
	"os"
	"path/filepath"
	"testing"
)

func TestConfigRoundTrip(t *testing.T) {
	// Redirect the user config dir into a temp HOME so the test never touches
	// the real ~/Library/Application Support.
	t.Setenv("HOME", t.TempDir())

	// Absent file → defaults.
	got, err := LoadConfig()
	if err != nil {
		t.Fatalf("LoadConfig (absent): %v", err)
	}
	if got != DefaultConfig() {
		t.Errorf("absent config should be defaults, got %+v", got)
	}

	want := DesktopConfig{ClipboardSyncEnabled: false, LaunchAtLogin: true}
	if err := SaveConfig(want); err != nil {
		t.Fatalf("SaveConfig: %v", err)
	}
	got, err = LoadConfig()
	if err != nil {
		t.Fatalf("LoadConfig: %v", err)
	}
	if got != want {
		t.Errorf("round-trip: got %+v, want %+v", got, want)
	}
}

func TestLoadConfigToleratesGarbage(t *testing.T) {
	t.Setenv("HOME", t.TempDir())
	p, err := configPath()
	if err != nil {
		t.Fatalf("configPath: %v", err)
	}
	if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(p, []byte("{not json"), 0o644); err != nil {
		t.Fatal(err)
	}
	got, err := LoadConfig()
	if err == nil {
		t.Error("expected an error for malformed json")
	}
	if got != DefaultConfig() {
		t.Errorf("malformed config should fall back to defaults, got %+v", got)
	}
}
