package infra

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

const wgTestConfig = `[Interface]
Address = 10.0.0.1/24
PrivateKey = SERVERKEY==

# DeviceID:device-001
[Peer]
PublicKey = PUBKEY001==
AllowedIPs = 10.0.0.2/32

# DeviceID:device-002
[Peer]
PublicKey = PUBKEY002==
AllowedIPs = 10.0.0.3/32
`

func writeTestConfig(t *testing.T, content string) string {
	t.Helper()
	dir := t.TempDir()
	path := filepath.Join(dir, "wg0.conf")
	if err := os.WriteFile(path, []byte(content), 0600); err != nil {
		t.Fatalf("write test config: %v", err)
	}
	return path
}

func TestWGPeerRemove(t *testing.T) {
	t.Run("peer present → status=removed", func(t *testing.T) {
		path := writeTestConfig(t, wgTestConfig)

		// Patch syncconf to no-op for tests (wg binary not available in CI).
		origSyncConf := wgSyncConfFn
		wgSyncConfFn = func(iface, configPath string) error { return nil }
		defer func() { wgSyncConfFn = origSyncConf }()

		result, err := WGPeerRemove("device-001", path)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if result.Status != WGPeerRemoveStatusRemoved {
			t.Errorf("got status=%q, want %q", result.Status, WGPeerRemoveStatusRemoved)
		}

		// Verify the peer block is gone from the file.
		data, _ := os.ReadFile(path)
		if strings.Contains(string(data), "DeviceID:device-001") {
			t.Error("DeviceID:device-001 marker still present after remove")
		}
		if strings.Contains(string(data), "PUBKEY001==") {
			t.Error("PUBKEY001 still present after remove")
		}
		// Other peer must remain.
		if !strings.Contains(string(data), "DeviceID:device-002") {
			t.Error("DeviceID:device-002 was incorrectly removed")
		}
	})

	t.Run("peer absent → status=not-present", func(t *testing.T) {
		path := writeTestConfig(t, wgTestConfig)

		origSyncConf := wgSyncConfFn
		wgSyncConfFn = func(iface, configPath string) error { return nil }
		defer func() { wgSyncConfFn = origSyncConf }()

		result, err := WGPeerRemove("device-999", path)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if result.Status != WGPeerRemoveStatusNotPresent {
			t.Errorf("got status=%q, want %q", result.Status, WGPeerRemoveStatusNotPresent)
		}

		// File must be unchanged.
		data, _ := os.ReadFile(path)
		if !strings.Contains(string(data), "DeviceID:device-001") {
			t.Error("existing peers were modified when removing absent peer")
		}
	})
}
