package dns

import (
	"fmt"
	"testing"

	"gotest.tools/v3/assert"
)

func TestEnsureDomainsResolveSameIPv4(t *testing.T) {
	tests := []struct {
		domainName     string
		serverName     string
		shouldValidate bool
	}{
		// NOTE(d1): DNS records get checked, so use something that is maintained
		// within the federation. if you're here because of a failing test, try
		// `dig +short <domain>` to ensure stuff matches first! If flakyness
		// becomes an issue we can look into mocking
		{"docs.coopcloud.tech", "coopcloud.tech", true},
		{"docs.coopcloud.tech", "swarm.autonomic.zone", true},

		// NOTE(d1): special case handling for "--local"
		{"", "default", true},
		{"", "local", true},

		{"", "", false},
		{"123", "", false},
	}

	for _, test := range tests {
		_, err := EnsureDomainsResolveSameIPv4(test.domainName, test.serverName)
		if err != nil && test.shouldValidate {
			t.Fatal(err)
		}

		if err == nil && !test.shouldValidate {
			t.Fatal(fmt.Errorf("should have failed but did not: %v", test))
		}
	}
}

func TestEnsureIpv4(t *testing.T) {
	// NOTE(d1): DNS records get checked, so use something that is maintained
	// within the federation. if you're here because of a failing test, try `dig
	// +short <domain>` to ensure stuff matches first! If flakyness becomes an
	// issue we can look into mocking
	domainName := "collabora.ostrom.collective.tools"
	serverName := "ostrom.collective.tools"

	for i := 0; i < 15; i++ {
		domainIpv4, err := EnsureIPv4(domainName)
		if err != nil {
			t.Fatal(err)
		}

		serverIpv4, err := EnsureIPv4(serverName)
		if err != nil {
			t.Fatal(err)
		}

		assert.Equal(t, domainIpv4, serverIpv4)
	}
}