package internal

import (
	"fmt"
	"time"

	"github.com/miekg/dns"
)

type Recursor struct {
	Upstreams []string
	Client    *dns.Client
}

type Resolved struct {
	RoundtripTime time.Duration
	UpstreamUsed  string
	Attempts      int
	Message       *dns.Msg
}

func (r Recursor) Resolve(request *dns.Msg) (Resolved, error) {
	var result Resolved
	errs := make([]error, len(r.Upstreams))
	var err error
	var upstreamsTried int

	for _, upstream := range r.Upstreams {
		result.Message, result.RoundtripTime, err = r.Client.Exchange(request, upstream)
		upstreamsTried++
		if err == nil {
			result.UpstreamUsed = upstream
			result.Message.RecursionAvailable = true
			break
		}
		errs = append(errs, err)
	}

	result.Attempts = upstreamsTried
	if result.Message == nil && len(errs) > 0 {
		return result, fmt.Errorf("errors occured resolving domain: %+v", errs)
	}

	return result, nil
}
