package dns

import (
	
	
	
	
	

	
)

// DNS origin and timeout defaults, matching iroh-dns/src/dns.rs.
const (
	// DNSTimeout is the default per-lookup timeout.
	DNSTimeout = 3 * time.Second
	// N0DNSEndpointOriginProd is the number0 production discovery origin.
	N0DNSEndpointOriginProd = "dns.iroh.link."
	// N0DNSEndpointOriginStaging is the number0 staging discovery origin.
	N0DNSEndpointOriginStaging = "staging-dns.iroh.link."
)

// TXTLookuper looks up the TXT records for a DNS name. It is the minimal
// resolver seam: any implementation (the stdlib-backed [Resolver], a DoH/DoT
// client, or a test fake) satisfies it.
//
// It is the Go analog of iroh's Resolver trait, narrowed to the TXT lookup that
// endpoint discovery needs.
type TXTLookuper interface {
	// LookupTXT returns the TXT record string values for name.
	LookupTXT(ctx context.Context, name string) ([]string, error)
}

// TXTLookuperFunc adapts a function to [TXTLookuper].
type TXTLookuperFunc func(ctx context.Context, name string) ([]string, error)

// LookupTXT calls f(ctx, name).
func ( TXTLookuperFunc) ( context.Context,  string) ([]string, error) {
	return (, )
}

// Resolver resolves iroh endpoint information from DNS. The zero value uses the
// host's default DNS configuration; set [Resolver.Lookuper] to override.
type Resolver struct {
	// Lookuper performs the underlying TXT lookups. If nil, a [net.Resolver]
	// with the default configuration is used.
	Lookuper TXTLookuper
}

func ( *Resolver) () TXTLookuper {
	if .Lookuper != nil {
		return .Lookuper
	}
	return netLookuper{}
}

// LookupEndpointByID resolves the endpoint info for id published under
// "_iroh.<z32-id>.<origin>". Pass [N0DNSEndpointOriginProd] for the number0
// production service.
func ( *Resolver) ( context.Context,  key.EndpointID,  string) (EndpointInfo, error) {
	 := IrohTXTName + "." + .Z32() + "." + ensureTrailingDot()
	return .LookupEndpointByDomainName(, )
}

// LookupEndpointByDomainName resolves the endpoint info from the TXT records at
// name, which must be of the form "_iroh.<z32-id>.<origin>".
func ( *Resolver) ( context.Context,  string) (EndpointInfo, error) {
	,  := context.WithTimeout(, DNSTimeout)
	defer ()
	,  := .lookuper().LookupTXT(, )
	if  != nil {
		return EndpointInfo{}, fmt.Errorf("lookup %q: %w", , )
	}
	return EndpointInfoFromTXTLookup(, )
}

// netLookuper is the default TXTLookuper, backed by the stdlib net.Resolver.
type netLookuper struct{}

func (netLookuper) ( context.Context,  string) ([]string, error) {
	return net.DefaultResolver.LookupTXT(, strings.TrimSuffix(, "."))
}

func ensureTrailingDot( string) string {
	if strings.HasSuffix(, ".") {
		return 
	}
	return  + "."
}