package api

// Group B — WG admin API auth + validation (Scenario C). Non-hollow: asserts store effects and
// fake-syncer call counts, not just statuses.

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"os"
	"strings"
	"sync"
	"testing"

	"gitea.dooplex.hu/admin/felhom-hub/internal/store"
	"gitea.dooplex.hu/admin/felhom-hub/internal/wgsync"
)

// fakeWGSyncer counts SyncNow/Trigger calls; err scripts the SyncNow result.
type fakeWGSyncer struct {
	syncCalls    int
	triggerCalls int
	err          error
}

func (f *fakeWGSyncer) SyncNow(ctx context.Context) error { f.syncCalls++; return f.err }
func (f *fakeWGSyncer) Trigger()                          { f.triggerCalls++ }

// testPK returns a VALID WG-shaped pubkey (44 std-base64 chars, 32 bytes) unique per fill byte.
func testPK(fill byte) string {
	return base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{fill}, 32))
}

func putTestEndpoint(t *testing.T, h *Handler) {
	t.Helper()
	body := `{"dns_name":"ep0.example","wg_port":443,"server_pubkey":"` + testPK(9) + `",` +
		`"tunnel_subnet":"10.77.0.0/24","pbs_tunnel_ip":"10.77.0.1"}`
	rr := do(h, http.MethodPut, "/admin/wg/endpoint", globalKey, body)
	if rr.Code != http.StatusOK {
		t.Fatalf("PUT endpoint = %d: %s", rr.Code, rr.Body.String())
	}
}

func TestWGPeers_PerHostKeyForbidden(t *testing.T) {
	h, st, _ := newTestHandler(t)
	st.UpsertHost(&store.Host{HostID: "h1", CustomerID: "c1", APIKey: "HKEY"})
	putTestEndpoint(t, h)
	fake := &fakeWGSyncer{}
	h.SetWGSyncer(fake)

	for _, m := range []string{http.MethodPost, http.MethodDelete, http.MethodGet} {
		rr := do(h, m, "/admin/wg/peers", "HKEY", `{"pubkey":"`+testPK(1)+`"}`)
		if rr.Code != http.StatusForbidden {
			t.Errorf("%s with per-host key = %d, want 403", m, rr.Code)
		}
	}
	rr := do(h, http.MethodPut, "/admin/wg/endpoint", "HKEY", `{}`)
	if rr.Code != http.StatusForbidden {
		t.Errorf("PUT endpoint with per-host key = %d, want 403", rr.Code)
	}
	peers, _ := st.ListWGPeers()
	if len(peers) != 0 {
		t.Errorf("rows created despite 403: %d", len(peers))
	}
	if fake.syncCalls != 0 {
		t.Errorf("sync ran despite 403: %d calls", fake.syncCalls)
	}
}

func TestWGPeers_AddHappyPath(t *testing.T) {
	h, st, _ := newTestHandler(t)
	putTestEndpoint(t, h)
	fake := &fakeWGSyncer{}
	h.SetWGSyncer(fake)

	rr := do(h, http.MethodPost, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(1)+`","note":"test"}`)
	if rr.Code != http.StatusOK {
		t.Fatalf("POST = %d: %s", rr.Code, rr.Body.String())
	}
	var resp struct {
		Pubkey     string `json:"pubkey"`
		AssignedIP string `json:"assigned_ip"`
		Existed    bool   `json:"existed"`
		Sync       string `json:"sync"`
	}
	json.Unmarshal(rr.Body.Bytes(), &resp)
	if resp.AssignedIP != "10.77.0.2/32" || resp.Existed || resp.Sync != "ok" {
		t.Errorf("resp = %+v, want .2/32 existed=false sync=ok", resp)
	}
	if fake.syncCalls != 1 {
		t.Errorf("sync calls = %d, want 1", fake.syncCalls)
	}
	peers, _ := st.ListWGPeers()
	if len(peers) != 1 || peers[0].AssignedIP != "10.77.0.2" || peers[0].Note != "test" {
		t.Errorf("stored peers = %+v", peers)
	}
}

func TestWGPeers_SyncDeferredOnPushFailure(t *testing.T) {
	h, _, _ := newTestHandler(t)
	putTestEndpoint(t, h)
	fake := &fakeWGSyncer{err: context.DeadlineExceeded}
	h.SetWGSyncer(fake)

	rr := do(h, http.MethodPost, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(1)+`"}`)
	if rr.Code != http.StatusOK {
		t.Fatalf("POST = %d (DB write is source of truth; push failure must not fail the request)", rr.Code)
	}
	var resp struct {
		Sync string `json:"sync"`
	}
	json.Unmarshal(rr.Body.Bytes(), &resp)
	if len(resp.Sync) < 8 || resp.Sync[:8] != "deferred" {
		t.Errorf("sync = %q, want deferred:...", resp.Sync)
	}
	if fake.triggerCalls != 1 {
		t.Errorf("Trigger calls = %d, want 1 (reconciler retry requested)", fake.triggerCalls)
	}
}

func TestWGPeers_SyncDisabledWhenUnwired(t *testing.T) {
	h, _, _ := newTestHandler(t)
	putTestEndpoint(t, h)
	// no SetWGSyncer — nil seam
	rr := do(h, http.MethodPost, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(1)+`"}`)
	if rr.Code != http.StatusOK {
		t.Fatalf("POST = %d", rr.Code)
	}
	var resp struct {
		Sync string `json:"sync"`
	}
	json.Unmarshal(rr.Body.Bytes(), &resp)
	if resp.Sync != "disabled" {
		t.Errorf("sync = %q, want disabled", resp.Sync)
	}
}

func TestWGPeers_BadPubkeyRejected(t *testing.T) {
	h, st, _ := newTestHandler(t)
	putTestEndpoint(t, h)
	bad := []string{
		"not-base64",
		base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 16)), // 24 chars
		"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",                 // 44 chars, not base64
		base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 33)), // 44 chars but 33 bytes
	}
	for _, pk := range bad {
		rr := do(h, http.MethodPost, "/admin/wg/peers", globalKey, `{"pubkey":"`+pk+`"}`)
		if rr.Code != http.StatusBadRequest {
			t.Errorf("pubkey %q = %d, want 400", pk, rr.Code)
		}
	}
	peers, _ := st.ListWGPeers()
	if len(peers) != 0 {
		t.Errorf("allocation happened for bad pubkey: %+v", peers)
	}
}

func TestWGPeers_NoEndpointIs409(t *testing.T) {
	h, _, _ := newTestHandler(t)
	rr := do(h, http.MethodPost, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(1)+`"}`)
	if rr.Code != http.StatusConflict {
		t.Errorf("POST without endpoint = %d, want 409", rr.Code)
	}
}

func TestWGEndpoint_PBSOutsideSubnetRejected(t *testing.T) {
	h, _, _ := newTestHandler(t)
	body := `{"dns_name":"ep0.example","wg_port":443,"server_pubkey":"` + testPK(9) + `",` +
		`"tunnel_subnet":"10.77.0.0/24","pbs_tunnel_ip":"10.88.0.1"}`
	rr := do(h, http.MethodPut, "/admin/wg/endpoint", globalKey, body)
	if rr.Code != http.StatusBadRequest {
		t.Errorf("PUT with pbs outside subnet = %d, want 400", rr.Code)
	}
	rr = do(h, http.MethodGet, "/admin/wg/endpoint", globalKey, "")
	if rr.Code != http.StatusNotFound {
		t.Errorf("GET after rejected PUT = %d, want 404 (nothing stored)", rr.Code)
	}
}

func TestWGPeers_DeleteUnknown404NoSync(t *testing.T) {
	h, _, _ := newTestHandler(t)
	putTestEndpoint(t, h)
	fake := &fakeWGSyncer{}
	h.SetWGSyncer(fake)
	rr := do(h, http.MethodDelete, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(7)+`"}`)
	if rr.Code != http.StatusNotFound {
		t.Errorf("DELETE unknown = %d, want 404", rr.Code)
	}
	if fake.syncCalls != 0 {
		t.Errorf("sync ran on 404 delete: %d", fake.syncCalls)
	}
}

// --- S2 Group B: registration endpoint + merge-at-read + admin-PUT rejection ---

// capturingPusher satisfies the wgsync push seam and records payload bytes — wiring a REAL
// wgsync.Reconciler over it lets API tests assert the actual pushed payload content.
type capturingPusher struct {
	mu       sync.Mutex
	payloads [][]byte
}

func (c *capturingPusher) Push(ctx context.Context, payload []byte) error {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.payloads = append(c.payloads, append([]byte(nil), payload...))
	return nil
}

func (c *capturingPusher) count() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return len(c.payloads)
}

func (c *capturingPusher) last() string {
	c.mu.Lock()
	defer c.mu.Unlock()
	if len(c.payloads) == 0 {
		return ""
	}
	return string(c.payloads[len(c.payloads)-1])
}

// putGoldenEndpoint sets the endpoint record with the EXACT values of the S2 wireguard golden.
func putGoldenEndpoint(t *testing.T, h *Handler) {
	t.Helper()
	body := `{"dns_name":"ep0.felhom.eu","wg_port":443,"server_pubkey":"` + testPK(9) + `",` +
		`"tunnel_subnet":"10.77.0.0/24","pbs_tunnel_ip":"10.77.0.1"}`
	if rr := do(h, http.MethodPut, "/admin/wg/endpoint", globalKey, body); rr.Code != http.StatusOK {
		t.Fatalf("PUT golden endpoint = %d: %s", rr.Code, rr.Body.String())
	}
}

func TestRegisterHostWG_FullFlowWithPerHostKey(t *testing.T) {
	h, st, _ := newTestHandler(t)
	seedHost(t, st, "h1", "c1", "HKEY1")
	putGoldenEndpoint(t, h)
	pusher := &capturingPusher{}
	h.SetWGSyncer(wgsync.NewReconciler(st, pusher, nil))

	rr := do(h, http.MethodPost, "/hosts/h1/wg", "HKEY1", `{"pubkey":"`+testPK(1)+`"}`)
	if rr.Code != http.StatusOK {
		t.Fatalf("register = %d: %s", rr.Code, rr.Body.String())
	}
	var resp struct {
		AssignedIP string `json:"assigned_ip"`
		Existed    bool   `json:"existed"`
		Generation int64  `json:"generation"`
		Sync       string `json:"sync"`
	}
	json.Unmarshal(rr.Body.Bytes(), &resp)
	if resp.AssignedIP != "10.77.0.2/32" || resp.Existed || resp.Generation != 1 || resp.Sync != "ok" {
		t.Errorf("resp = %+v, want .2/32 existed=false gen=1 sync=ok", resp)
	}
	if pusher.count() != 1 || !strings.Contains(pusher.last(), testPK(1)) {
		t.Errorf("pushed payloads = %d, last = %s — want 1 push containing the pubkey", pusher.count(), pusher.last())
	}
	// Idempotent re-register: generation UNCHANGED, NO new push (both negatives).
	rr = do(h, http.MethodPost, "/hosts/h1/wg", "HKEY1", `{"pubkey":"`+testPK(1)+`"}`)
	json.Unmarshal(rr.Body.Bytes(), &resp)
	if rr.Code != http.StatusOK || !resp.Existed || resp.Generation != 1 || resp.Sync != "unchanged" {
		t.Errorf("idempotent = %d %+v, want existed=true gen-still-1 sync=unchanged", rr.Code, resp)
	}
	if pusher.count() != 1 {
		t.Errorf("push count after idempotent re-register = %d, want still 1", pusher.count())
	}
	// Re-key: pubkey swapped in place, ip kept, generation bumped, payload has P2 and NOT P1.
	rr = do(h, http.MethodPost, "/hosts/h1/wg", "HKEY1", `{"pubkey":"`+testPK(2)+`"}`)
	json.Unmarshal(rr.Body.Bytes(), &resp)
	if rr.Code != http.StatusOK || resp.AssignedIP != "10.77.0.2/32" || resp.Existed || resp.Generation != 2 {
		t.Errorf("re-key = %d %+v, want ip kept, gen=2", rr.Code, resp)
	}
	if pusher.count() != 2 || !strings.Contains(pusher.last(), testPK(2)) || strings.Contains(pusher.last(), testPK(1)) {
		t.Errorf("re-key payload = %s — must contain P2, not P1", pusher.last())
	}
}

func TestRegisterHostWG_SelfScopeAndConflicts(t *testing.T) {
	h, st, _ := newTestHandler(t)
	seedHost(t, st, "h1", "c1", "HKEY1")
	seedHost(t, st, "h2", "c2", "HKEY2")
	fake := &fakeWGSyncer{}
	h.SetWGSyncer(fake)

	// c4: no endpoint record yet → 409, no allocation.
	if rr := do(h, http.MethodPost, "/hosts/h1/wg", "HKEY1", `{"pubkey":"`+testPK(1)+`"}`); rr.Code != http.StatusConflict {
		t.Errorf("register without endpoint = %d, want 409", rr.Code)
	}
	putGoldenEndpoint(t, h)

	// c1: h2's key on h1's path → 403, no row, no sync.
	if rr := do(h, http.MethodPost, "/hosts/h1/wg", "HKEY2", `{"pubkey":"`+testPK(1)+`"}`); rr.Code != http.StatusForbidden {
		t.Errorf("cross-host register = %d, want 403", rr.Code)
	}
	if peers, _ := st.ListWGPeers(); len(peers) != 0 {
		t.Errorf("rows after 403 = %d, want 0", len(peers))
	}
	if fake.syncCalls != 0 {
		t.Errorf("sync ran on refused register: %d", fake.syncCalls)
	}
	// no auth → 401
	if rr := do(h, http.MethodPost, "/hosts/h1/wg", "", `{"pubkey":"`+testPK(1)+`"}`); rr.Code != http.StatusUnauthorized {
		t.Errorf("no-auth register = %d, want 401", rr.Code)
	}
	// c3: unknown host (global key so the self-scope gate passes) → 404.
	if rr := do(h, http.MethodPost, "/hosts/ghost/wg", globalKey, `{"pubkey":"`+testPK(1)+`"}`); rr.Code != http.StatusNotFound {
		t.Errorf("unknown host = %d, want 404", rr.Code)
	}
	// c2: pubkey bound to h2 → h1 registering it → 409.
	if rr := do(h, http.MethodPost, "/hosts/h2/wg", "HKEY2", `{"pubkey":"`+testPK(1)+`"}`); rr.Code != http.StatusOK {
		t.Fatalf("h2 register = %d", rr.Code)
	}
	if rr := do(h, http.MethodPost, "/hosts/h1/wg", "HKEY1", `{"pubkey":"`+testPK(1)+`"}`); rr.Code != http.StatusConflict {
		t.Errorf("stealing h2's pubkey = %d, want 409", rr.Code)
	}
	// bad pubkey → 400
	if rr := do(h, http.MethodPost, "/hosts/h1/wg", "HKEY1", `{"pubkey":"nope"}`); rr.Code != http.StatusBadRequest {
		t.Errorf("bad pubkey = %d, want 400", rr.Code)
	}
}

func TestDesiredState_WireguardMergeMatchesGolden(t *testing.T) {
	h, st, _ := newTestHandler(t)
	seedHost(t, st, "h1", "c1", "HKEY1")
	putGoldenEndpoint(t, h)
	h.SetWGSyncer(&fakeWGSyncer{})

	// Operator sets the EXISTING golden's desired_state (the operator blob half).
	raw, err := os.ReadFile("testdata/desired-state.golden.json")
	if err != nil {
		t.Fatal(err)
	}
	var base struct {
		DesiredState json.RawMessage `json:"desired_state"`
	}
	json.Unmarshal(raw, &base)
	if rr := do(h, http.MethodPut, "/admin/hosts/h1/desired-state", globalKey, string(base.DesiredState)); rr.Code != http.StatusOK {
		t.Fatalf("admin-set: %d", rr.Code)
	}
	// Box registers → the served state must equal the NEW golden (base + wireguard block).
	if rr := do(h, http.MethodPost, "/hosts/h1/wg", "HKEY1", `{"pubkey":"`+testPK(1)+`"}`); rr.Code != http.StatusOK {
		t.Fatalf("register: %d", rr.Code)
	}

	// This file is the S3 CROSS-REPO CONTRACT — the agent's testdata copy must stay
	// byte-identical (the desired-state.golden.json duplication rule).
	wgGolden, err := os.ReadFile("testdata/desired-state-wireguard.golden.json")
	if err != nil {
		t.Fatal(err)
	}
	var want struct {
		DesiredState json.RawMessage `json:"desired_state"`
	}
	json.Unmarshal(wgGolden, &want)

	rr := do(h, http.MethodGet, "/hosts/h1/desired-state", "HKEY1", "")
	if rr.Code != 200 {
		t.Fatalf("GET: %d", rr.Code)
	}
	var got struct {
		Generation   int64           `json:"generation"`
		DesiredState json.RawMessage `json:"desired_state"`
	}
	json.Unmarshal(rr.Body.Bytes(), &got)
	if got.Generation != 2 { // admin-set (1) + registration bump (2)
		t.Errorf("generation = %d, want 2", got.Generation)
	}
	var wantAny, gotAny any
	json.Unmarshal(want.DesiredState, &wantAny)
	json.Unmarshal(got.DesiredState, &gotAny)
	wb, _ := json.Marshal(wantAny)
	gb, _ := json.Marshal(gotAny)
	if string(wb) != string(gb) {
		t.Errorf("served desired_state != wireguard golden:\n want: %s\n got:  %s", wb, gb)
	}

	// Stored-blob purity: the raw stored desired_json is BYTE-identical to what the operator PUT.
	host, _ := st.GetHost("h1")
	if host.DesiredJSON != string(base.DesiredState) {
		t.Errorf("stored desired_json was modified by the merge:\n stored: %s\n put:    %s", host.DesiredJSON, base.DesiredState)
	}
}

// H1: with a fleet operator OOB peer registered, a host's served wireguard block carries oob_peer_ip
// (the operator's /32) so the agent renders it into AllowedIPs. Without it, no key (byte-identical —
// covered by TestDesiredState_WireguardMergeMatchesGolden).
func TestDesiredState_IncludesOOBPeerIPWhenOperatorRegistered(t *testing.T) {
	h, st, _ := newTestHandler(t)
	seedHost(t, st, "h1", "c1", "HKEY1")
	putGoldenEndpoint(t, h)
	h.SetWGSyncer(&fakeWGSyncer{})
	if rr := do(h, http.MethodPost, "/hosts/h1/wg", "HKEY1", `{"pubkey":"`+testPK(1)+`"}`); rr.Code != 200 {
		t.Fatalf("register: %d", rr.Code)
	}

	// no operator peer yet → served block has NO oob_peer_ip
	got := servedWG(t, h)
	if _, has := got["oob_peer_ip"]; has {
		t.Fatalf("oob_peer_ip present with no operator peer: %v", got)
	}

	// register the operator peer (global key)
	if rr := do(h, http.MethodPut, "/admin/wg/operator-peer", globalKey,
		`{"pubkey":"`+opTestPubkey+`","assigned_ip":"10.77.0.250"}`); rr.Code != 200 {
		t.Fatalf("set operator peer: %d %s", rr.Code, servedBody(t, h))
	}
	got = servedWG(t, h)
	if got["oob_peer_ip"] != "10.77.0.250" {
		t.Fatalf("served oob_peer_ip = %v, want 10.77.0.250", got["oob_peer_ip"])
	}

	// read-back route
	if rr := do(h, http.MethodGet, "/admin/wg/operator-peer", globalKey, ""); rr.Code != 200 {
		t.Fatalf("operator-peer read-back: %d", rr.Code)
	}
	// a per-host key cannot set the operator peer
	if rr := do(h, http.MethodPut, "/admin/wg/operator-peer", "HKEY1",
		`{"pubkey":"`+opTestPubkey+`","assigned_ip":"10.77.0.248"}`); rr.Code != 403 {
		t.Fatalf("host key setting operator peer must be 403, got %d", rr.Code)
	}
}

const opTestPubkey = "cdmN4U+fjR18zBk+SKoceJQyz9HgA9+hN8/FiKF1u0o="

func servedWG(t *testing.T, h *Handler) map[string]any {
	t.Helper()
	rr := do(h, http.MethodGet, "/hosts/h1/desired-state", "HKEY1", "")
	if rr.Code != 200 {
		t.Fatalf("GET desired-state: %d", rr.Code)
	}
	var got struct {
		DesiredState json.RawMessage `json:"desired_state"`
	}
	json.Unmarshal(rr.Body.Bytes(), &got)
	var doc map[string]any
	json.Unmarshal(got.DesiredState, &doc)
	wg, _ := doc["wireguard"].(map[string]any)
	if wg == nil {
		t.Fatalf("no wireguard block in served state: %s", got.DesiredState)
	}
	return wg
}

func servedBody(t *testing.T, h *Handler) string {
	return do(h, http.MethodGet, "/hosts/h1/desired-state", "HKEY1", "").Body.String()
}

func TestAdminSetDesiredState_RejectsWireguardKey(t *testing.T) {
	h, st, _ := newTestHandler(t)
	seedHost(t, st, "h1", "c1", "HKEY1")
	putGoldenEndpoint(t, h)

	fake := `{"guests":[],"wireguard":{"pubkey":"FAKE","assigned_ip":"10.77.0.99/32"}}`
	rr := do(h, http.MethodPut, "/admin/hosts/h1/desired-state", globalKey, fake)
	if rr.Code != http.StatusBadRequest {
		t.Fatalf("PUT with wireguard key = %d, want 400", rr.Code)
	}
	if !strings.Contains(rr.Body.String(), "hub-owned") {
		t.Errorf("rejection message = %q, want the hub-owned hint", rr.Body.String())
	}
	// Follow-up GET must NOT serve the fake block (nothing was stored; no peer registered).
	rr = do(h, http.MethodGet, "/hosts/h1/desired-state", "HKEY1", "")
	if strings.Contains(rr.Body.String(), "FAKE") || strings.Contains(rr.Body.String(), "wireguard") {
		t.Errorf("GET serves a wireguard block that was never legitimately registered: %s", rr.Body.String())
	}
	// Generation untouched by the refused PUT.
	host, _ := st.GetHost("h1")
	if host.DesiredGeneration != 0 {
		t.Errorf("generation moved on refused PUT: %d", host.DesiredGeneration)
	}
}

func TestAdminDeleteWGPeer_BumpsOwnerOnlyForBoundPeers(t *testing.T) {
	h, st, _ := newTestHandler(t)
	seedHost(t, st, "h1", "c1", "HKEY1")
	putGoldenEndpoint(t, h)
	h.SetWGSyncer(&fakeWGSyncer{})

	// Bound peer: register (gen 1) then admin-delete → gen 2, GET has no wireguard key.
	do(h, http.MethodPost, "/hosts/h1/wg", "HKEY1", `{"pubkey":"`+testPK(1)+`"}`)
	rr := do(h, http.MethodDelete, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(1)+`"}`)
	if rr.Code != http.StatusOK {
		t.Fatalf("delete bound = %d", rr.Code)
	}
	host, _ := st.GetHost("h1")
	if host.DesiredGeneration != 2 {
		t.Errorf("generation after bound delete = %d, want 2 (register+delete)", host.DesiredGeneration)
	}
	rr = do(h, http.MethodGet, "/hosts/h1/desired-state", "HKEY1", "")
	if strings.Contains(rr.Body.String(), "wireguard") {
		t.Errorf("GET still serves wireguard after peer delete: %s", rr.Body.String())
	}

	// Unbound peer: admin add + delete → NO host generation movement (the negative).
	do(h, http.MethodPost, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(3)+`"}`)
	do(h, http.MethodDelete, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(3)+`"}`)
	host, _ = st.GetHost("h1")
	if host.DesiredGeneration != 2 {
		t.Errorf("unbound add/delete moved h1's generation: %d, want still 2", host.DesiredGeneration)
	}
}

func TestWGPeers_DeleteKnownRemovesAndSyncs(t *testing.T) {
	h, st, _ := newTestHandler(t)
	putTestEndpoint(t, h)
	fake := &fakeWGSyncer{}
	h.SetWGSyncer(fake)
	do(h, http.MethodPost, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(1)+`"}`)
	do(h, http.MethodPost, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(2)+`"}`)

	rr := do(h, http.MethodDelete, "/admin/wg/peers", globalKey, `{"pubkey":"`+testPK(1)+`"}`)
	if rr.Code != http.StatusOK {
		t.Fatalf("DELETE = %d: %s", rr.Code, rr.Body.String())
	}
	peers, _ := st.ListWGPeers()
	if len(peers) != 1 || peers[0].Pubkey != testPK(2) {
		t.Errorf("peers after delete = %+v, want only p2", peers)
	}
	if fake.syncCalls != 3 { // 2 adds + 1 delete
		t.Errorf("sync calls = %d, want 3", fake.syncCalls)
	}
}
