//go:build darwin

package platform

import (
	"os"
	"strings"
	"testing"
)

func TestSetLaunchAtLoginInstallsAndRemoves(t *testing.T) {
	t.Setenv("HOME", t.TempDir())

	if IsLaunchAtLoginEnabled() {
		t.Fatal("should start disabled")
	}

	if err := SetLaunchAtLogin(true); err != nil {
		t.Fatalf("enable: %v", err)
	}
	if !IsLaunchAtLoginEnabled() {
		t.Error("should be enabled after install")
	}

	p, _ := launchAgentPath()
	data, err := os.ReadFile(p)
	if err != nil {
		t.Fatalf("read plist: %v", err)
	}
	plist := string(data)
	if !strings.Contains(plist, "<key>Label</key>") ||
		!strings.Contains(plist, launchAgentLabel) ||
		!strings.Contains(plist, "<key>RunAtLoad</key>") {
		t.Errorf("plist missing expected keys:\n%s", plist)
	}

	// Disabling removes the file; removing again is a no-op success.
	if err := SetLaunchAtLogin(false); err != nil {
		t.Fatalf("disable: %v", err)
	}
	if IsLaunchAtLoginEnabled() {
		t.Error("should be disabled after removal")
	}
	if err := SetLaunchAtLogin(false); err != nil {
		t.Errorf("removing an absent agent should be a no-op, got %v", err)
	}
}

func TestAppBundlePath(t *testing.T) {
	cases := map[string]string{
		"/Apps/cdrop.app/Contents/MacOS/desktop": "/Apps/cdrop.app",
		"/usr/local/bin/desktop":                 "",
	}
	for in, want := range cases {
		if got := appBundlePath(in); got != want {
			t.Errorf("appBundlePath(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestXMLEscape(t *testing.T) {
	got := xmlEscape(`a&b<c>"d"`)
	if !strings.Contains(got, "&amp;") || !strings.Contains(got, "&lt;") || !strings.Contains(got, "&quot;") {
		t.Errorf("xmlEscape did not escape specials: %q", got)
	}
}
