package file

import (
	"sort"
	"strings"
	"testing"

	"github.com/miekg/coredns/middleware/pkg/dnsrecorder"
	"github.com/miekg/coredns/middleware/test"

	"github.com/miekg/dns"
	"golang.org/x/net/context"
)

var wildcardTestCases = []test.Case{
	{
		Qname: "wild.dnssex.nl.", Qtype: dns.TypeTXT,
		Answer: []dns.RR{
			test.TXT(`wild.dnssex.nl.	1800	IN	TXT	"Doing It Safe Is Better"`),
		},
	},
	{
		Qname: "a.wild.dnssex.nl.", Qtype: dns.TypeTXT,
		Answer: []dns.RR{
			test.TXT(`a.wild.dnssex.nl.	1800	IN	TXT	"Doing It Safe Is Better"`),
		},
	},
	{
		Qname: "wild.dnssex.nl.", Qtype: dns.TypeTXT, Do: true,
		Answer: []dns.RR{
			test.RRSIG("wild.dnssex.nl.	1800	IN	RRSIG	TXT 8 2 1800 20160428190224 20160329190224 14460 dnssex.nl. FUZSTyvZfeuuOpCm"),
			test.TXT(`wild.dnssex.nl.	1800	IN	TXT	"Doing It Safe Is Better"`),
		},
		Ns: []dns.RR{
			test.NSEC("a.dnssex.nl.	14400	IN	NSEC	www.dnssex.nl. A AAAA RRSIG NSEC"),
			test.RRSIG("a.dnssex.nl.	14400	IN	RRSIG	NSEC 8 3 14400 20160428190224 20160329190224 14460 dnssex.nl. S+UMs2ySgRaaRY"),
		},
		Extra: []dns.RR{test.OPT(4096, true)},
	},
	{
		Qname: "a.wild.dnssex.nl.", Qtype: dns.TypeTXT, Do: true,
		Answer: []dns.RR{
			test.RRSIG("a.wild.dnssex.nl.	1800	IN	RRSIG	TXT 8 2 1800 20160428190224 20160329190224 14460 dnssex.nl. FUZSTyvZfeuuOpCm"),
			test.TXT(`a.wild.dnssex.nl.	1800	IN	TXT	"Doing It Safe Is Better"`),
		},
		Ns: []dns.RR{
			test.NSEC("a.dnssex.nl.	14400	IN	NSEC	www.dnssex.nl. A AAAA RRSIG NSEC"),
			test.RRSIG("a.dnssex.nl.	14400	IN	RRSIG	NSEC 8 3 14400 20160428190224 20160329190224 14460 dnssex.nl. S+UMs2ySgRaaRY"),
		},
		Extra: []dns.RR{test.OPT(4096, true)},
	},
	// nodata responses
	{
		Qname: "wild.dnssex.nl.", Qtype: dns.TypeSRV,
		Ns: []dns.RR{
			test.SOA(`dnssex.nl.	1800	IN	SOA	linode.atoom.net. miek.miek.nl. 1459281744 14400 3600 604800 14400`),
		},
	},
	{
		Qname: "wild.dnssex.nl.", Qtype: dns.TypeSRV, Do: true,
		Ns: []dns.RR{
			// TODO(miek): needs closest encloser proof as well? This is the wrong answer
			test.NSEC(`*.dnssex.nl.	14400	IN	NSEC	a.dnssex.nl. TXT RRSIG NSEC`),
			test.RRSIG(`*.dnssex.nl.	14400	IN	RRSIG	NSEC 8 2 14400 20160428190224 20160329190224 14460 dnssex.nl. os6INm6q2eXknD5z8TpfbK00uxVbQefMvHcR/RNX/kh0xXvzAaaDOV+Ge/Ko+2dXnKP+J1LYG9ffXNpdbaQy5ygzH5F041GJst4566GdG/jt7Z7vLHYxEBTpZfxo+PLsXQXH3VTemZyuWyDfqJzafXJVH1F0nDrcXmMlR6jlBHA=`),
			test.RRSIG(`dnssex.nl.	1800	IN	RRSIG	SOA 8 2 1800 20160428190224 20160329190224 14460 dnssex.nl. CA/Y3m9hCOiKC/8ieSOv8SeP964BUdG/8MC3WtKljUosK9Z9bBGrVizDjjqgq++lyH8BZJcTaabAsERs4xj5PRtcxicwQXZACX5VYjXHQeZmCyytFU5wq2gcXSmvUH86zZzftx3RGPvn1aOoTlcvoC3iF8fYUCpROlUS0YR8Cdw=`),
			test.SOA(`dnssex.nl.	1800	IN	SOA	linode.atoom.net. miek.miek.nl. 1459281744 14400 3600 604800 14400`),
		},
		Extra: []dns.RR{test.OPT(4096, true)},
	},
}

func TestLookupWildcard(t *testing.T) {
	zone, err := Parse(strings.NewReader(dbDnssexNLSigned), testzone1, "stdin")
	if err != nil {
		t.Fatalf("Expect no error when reading zone, got %q", err)
	}

	fm := File{Next: test.ErrorHandler(), Zones: Zones{Z: map[string]*Zone{testzone1: zone}, Names: []string{testzone1}}}
	ctx := context.TODO()

	for _, tc := range wildcardTestCases {
		m := tc.Msg()

		rec := dnsrecorder.New(&test.ResponseWriter{})
		_, err := fm.ServeDNS(ctx, rec, m)
		if err != nil {
			t.Errorf("Expected no error, got %v\n", err)
			return
		}

		resp := rec.Msg
		sort.Sort(test.RRSet(resp.Answer))
		sort.Sort(test.RRSet(resp.Ns))
		sort.Sort(test.RRSet(resp.Extra))

		if !test.Header(t, tc, resp) {
			t.Logf("%v\n", resp)
			continue
		}
		if !test.Section(t, tc, test.Answer, resp.Answer) {
			t.Logf("%v\n", resp)
		}
		if !test.Section(t, tc, test.Ns, resp.Ns) {
			t.Logf("%v\n", resp)
		}
		if !test.Section(t, tc, test.Extra, resp.Extra) {
			t.Logf("%v\n", resp)
		}
	}
}

var wildcardDoubleTestCases = []test.Case{
	{
		Qname: "wild.w.example.org.", Qtype: dns.TypeTXT,
		Answer: []dns.RR{
			test.TXT(`wild.w.example.org. IN	TXT	"Wildcard"`),
		},
	},
	{
		Qname: "wild.c.example.org.", Qtype: dns.TypeTXT,
		Answer: []dns.RR{
			test.TXT(`wild.c.example.org. IN	TXT	"c Wildcard"`),
		},
	},
	{
		Qname: "wild.d.example.org.", Qtype: dns.TypeTXT,
		Answer: []dns.RR{
			test.TXT(`alias.example.org. IN	TXT	"Wildcard CNAME expansion"`),
			test.CNAME(`wild.d.example.org. IN	CNAME	alias.example.org`),
		},
	},
	{
		Qname: "alias.example.org.", Qtype: dns.TypeTXT,
		Answer: []dns.RR{
			test.TXT(`alias.example.org. IN	TXT	"Wildcard CNAME expansion"`),
		},
	},
}

func TestLookupDoubleWildcard(t *testing.T) {
	zone, err := Parse(strings.NewReader(exampleOrg), "example.org.", "stdin")
	if err != nil {
		t.Fatalf("Expect no error when reading zone, got %q", err)
	}

	fm := File{Next: test.ErrorHandler(), Zones: Zones{Z: map[string]*Zone{"example.org.": zone}, Names: []string{"example.org."}}}
	ctx := context.TODO()

	for _, tc := range wildcardDoubleTestCases {
		m := tc.Msg()

		rec := dnsrecorder.New(&test.ResponseWriter{})
		_, err := fm.ServeDNS(ctx, rec, m)
		if err != nil {
			t.Errorf("Expected no error, got %v\n", err)
			return
		}

		resp := rec.Msg
		sort.Sort(test.RRSet(resp.Answer))
		sort.Sort(test.RRSet(resp.Ns))
		sort.Sort(test.RRSet(resp.Extra))

		if !test.Header(t, tc, resp) {
			t.Logf("%v\n", resp)
			continue
		}
		if !test.Section(t, tc, test.Answer, resp.Answer) {
			t.Logf("%v\n", resp)
		}
		if !test.Section(t, tc, test.Ns, resp.Ns) {
			t.Logf("%v\n", resp)
		}
		if !test.Section(t, tc, test.Extra, resp.Extra) {
			t.Logf("%v\n", resp)
		}
	}
}

func TestReplaceWithAsteriskLabel(t *testing.T) {
	tests := []struct {
		in, out string
	}{
		{".", ""},
		{"miek.nl.", "*.nl."},
		{"www.miek.nl.", "*.miek.nl."},
	}

	for _, tc := range tests {
		got := replaceWithAsteriskLabel(tc.in)
		if got != tc.out {
			t.Errorf("Expected to be %s, got %s", tc.out, got)
		}
	}
}

const exampleOrg = `; example.org test file
example.org.		IN	SOA	sns.dns.icann.org. noc.dns.icann.org. 2015082541 7200 3600 1209600 3600
example.org.		IN	NS	b.iana-servers.net.
example.org.		IN	NS	a.iana-servers.net.
example.org.		IN	A	127.0.0.1
example.org.		IN	A	127.0.0.2
*.w.example.org.        IN      TXT     "Wildcard"
a.b.c.w.example.org.    IN      TXT     "Not a wildcard"
*.c.example.org.        IN      TXT     "c Wildcard"
*.d.example.org.        IN      CNAME   alias.example.org.
alias.example.org.      IN      TXT     "Wildcard CNAME expansion"
`
