package dns

import (
	"errors"
	"net"

	"coopcloud.tech/abra/pkg/i18n"
)

// EnsureIPv4 ensures that an ipv4 address is set for a domain name
func EnsureIPv4(domainName string) (string, error) {
	ipv4, err := net.ResolveIPAddr("ip4", domainName)
	if err != nil {
		return "", errors.New(i18n.G("%s: unable to resolve IPv4 address: %s", domainName, err))
	}

	if ipv4 == nil {
		return "", errors.New(i18n.G("%s: no IPv4 available", domainName))
	}

	return ipv4.String(), nil
}

// EnsureDomainsResolveSameIPv4 ensures that domains resolve to the same ipv4 address
func EnsureDomainsResolveSameIPv4(domainName, server string) (string, error) {
	if server == "default" || server == "local" {
		return "", nil
	}

	var ipv4 string

	domainIPv4, err := EnsureIPv4(domainName)
	if err != nil {
		return ipv4, err
	}

	if domainIPv4 == "" {
		return ipv4, errors.New(i18n.G("cannot resolve ipv4 for %s?", domainName))
	}

	serverIPv4, err := EnsureIPv4(server)
	if err != nil {
		return ipv4, err
	}

	if serverIPv4 == "" {
		return ipv4, errors.New(i18n.G("cannot resolve ipv4 for %s?", server))
	}

	if domainIPv4 != serverIPv4 {
		return ipv4, errors.New(
			i18n.G(
				"app domain %s (%s) does not appear to resolve to app server %s (%s)?",
				domainName, domainIPv4, server, serverIPv4,
			),
		)
	}

	return ipv4, nil
}
