package autoconfig

import (
	"context"
	"net"
	"sort"
	"strings"
)

func lookupMX(ctx context.Context, domain string) ([]string, error) {
	resolver := net.Resolver{}
	mxRecords, err := resolver.LookupMX(ctx, domain)
	if err != nil {
		return nil, err
	}
	sort.Slice(mxRecords, func(i, j int) bool {
		return mxRecords[i].Pref < mxRecords[j].Pref
	})
	hosts := make([]string, 0, len(mxRecords))
	for _, mx := range mxRecords {
		host := strings.TrimSuffix(strings.ToLower(mx.Host), ".")
		if host != "" {
			hosts = append(hosts, host)
		}
	}
	return hosts, nil
}

func discoverFromMX(ctx context.Context, email, domain string) (Result, bool) {
	hosts, err := lookupMX(ctx, domain)
	if err != nil || len(hosts) == 0 {
		return Result{}, false
	}
	for _, host := range hosts {
		if preset, ok := matchMX(host); ok {
			r := preset.toResult(email, domain, "mx", "high")
			r.Notes = append(r.Notes, "Configuration déduite des enregistrements MX («"+host+"»).")
			return r, true
		}
	}
	return Result{}, false
}
