package l7

import (
	"strings"

	"golang.org/x/net/dns/dnsmessage"
	"inet.af/netaddr"
)

func ParseDns(payload []byte) (string, string, uint32, []netaddr.IP) {
	var msg dnsmessage.Message
	if err := msg.Unpack(payload); err != nil {
		return "", "", 0, nil
	}
	if len(msg.Questions) < 1 {
		return "", "", 0, nil
	}
	var ips []netaddr.IP
	var ttl uint32
	for _, a := range msg.Answers {
		ttl = a.Header.TTL
		switch a.Header.Type {
		case dnsmessage.TypeA:
			if r, ok := a.Body.(*dnsmessage.AResource); ok {
				ips = append(ips, netaddr.IPFrom4(r.A))
			}
		case dnsmessage.TypeAAAA:
			if r, ok := a.Body.(*dnsmessage.AAAAResource); ok {
				ips = append(ips, netaddr.IPFrom16(r.AAAA))
			}
		}
	}
	//if len(msg.Answers) == 0 {
	//	for _, a := range msg.Authorities {
	//		ttl = a.Header.TTL
	//	}
	//}

	q := msg.Questions[0]
	qType := q.Type.String()
	if len(qType) > 4 {
		qType = qType[4:]
	}
	//fmt.Println("gostring", msg.GoString())
	return qType, strings.TrimSuffix(q.Name.String(), "."), ttl, ips
}
