package vmdns

import (
	"testing"
)

func TestServerRemoveDropsRecord(t *testing.T) {
	server := startTestServer(t)
	if err := server.Set("devbox.vm", "172.16.0.8"); err != nil {
		t.Fatalf("Set: %v", err)
	}
	if _, ok := server.Lookup("devbox.vm"); !ok {
		t.Fatal("record missing before remove")
	}

	if err := server.Remove("devbox.vm"); err != nil {
		t.Fatalf("Remove: %v", err)
	}
	if _, ok := server.Lookup("devbox.vm"); ok {
		t.Fatal("record still present after Remove")
	}
}

func TestServerRemoveInvalidNameIsNoop(t *testing.T) {
	server := startTestServer(t)
	// Non-.vm names silently normalize-fail, returning nil.
	if err := server.Remove("example.com"); err != nil {
		t.Fatalf("Remove: %v", err)
	}
}

func TestServerRemoveNilReceiver(t *testing.T) {
	var s *Server
	if err := s.Remove("anything.vm"); err != nil {
		t.Fatalf("nil Remove: %v", err)
	}
}

func TestServerSetRejectsIPv6(t *testing.T) {
	server := startTestServer(t)
	if err := server.Set("six.vm", "::1"); err == nil {
		t.Fatal("expected error for IPv6 address")
	}
}

func TestServerSetRejectsBadIP(t *testing.T) {
	server := startTestServer(t)
	if err := server.Set("bad.vm", "not-an-ip"); err == nil {
		t.Fatal("expected parse error for bogus IP")
	}
}

func TestServerSetRejectsNonVMName(t *testing.T) {
	server := startTestServer(t)
	if err := server.Set("example.com", "172.16.0.1"); err == nil {
		t.Fatal("expected error for non-.vm name")
	}
}

func TestServerReplaceRejectsBadIP(t *testing.T) {
	server := startTestServer(t)
	err := server.Replace(map[string]string{"bad.vm": "nope"})
	if err == nil {
		t.Fatal("expected parse error")
	}
}

func TestServerReplaceRejectsIPv6(t *testing.T) {
	server := startTestServer(t)
	err := server.Replace(map[string]string{"six.vm": "::1"})
	if err == nil {
		t.Fatal("expected IPv6 rejection")
	}
}

func TestServerNilLookupAndAddr(t *testing.T) {
	var s *Server
	if _, ok := s.Lookup("x.vm"); ok {
		t.Fatal("nil Lookup should return false")
	}
	if got := s.Addr(); got != "" {
		t.Fatalf("nil Addr = %q, want empty", got)
	}
	if err := s.Close(); err != nil {
		t.Fatalf("nil Close: %v", err)
	}
	if err := s.Set("x.vm", "172.16.0.1"); err != nil {
		t.Fatalf("nil Set: %v", err)
	}
	if err := s.Replace(map[string]string{"x.vm": "172.16.0.1"}); err != nil {
		t.Fatalf("nil Replace: %v", err)
	}
}
