package mask

import (
	"strings"
	"testing"

	"github.com/stretchr/testify/require"
)

type matches uint8

const (
	whole matches = 1 << iota
	inMiddle
	atStart
	atEnd
)

const allMatches matches = whole ^ inMiddle ^ atStart ^ atEnd
const noMatches matches = 0

func TestIsSensitiveParam(t *testing.T) {
	tests := []struct {
		name string
		want matches
	}{
		{"token", whole ^ atEnd},
		{"password", allMatches},
		{"secret", allMatches},
		{"key", whole ^ atEnd},
		{"signature", allMatches},
		{"authorization", whole},
		{"certificate", whole},
		{"encrypted_key", whole ^ atEnd},
		{"hook", whole},
		{"import_url", whole},
		{"elasticsearch_url", whole},
		{"otp_attempt", whole},
		{"sentry_dsn", whole},
		{"trace", whole},
		{"variables", whole},
		{"content", whole},
		{"body", whole},
		{"description", whole},
		{"note", whole},
		{"text", whole},
		{"title", whole},
		{"gitlab", noMatches},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			check := func(v string) {
				// Normal case
				gotWhole := IsSensitiveParam(v)
				require.Equal(t, tt.want&whole != 0, gotWhole, "Whole param match on '%s'", v)

				gotMiddle := IsSensitiveParam("prefix" + v + "suffix")
				require.Equal(t, tt.want&inMiddle != 0, gotMiddle, "Middle match on '%s'", "prefix"+v+"suffix")

				gotStart := IsSensitiveParam(v + "suffix")
				require.Equal(t, tt.want&atStart != 0, gotStart, "Start match on '%s'", v+"suffix")

				gotEnd := IsSensitiveParam("prefix" + v)
				require.Equal(t, tt.want&atEnd != 0, gotEnd, "End match on '%s'", "prefix"+v)
			}

			check(tt.name)
			check(strings.ToUpper(tt.name))
			check(strings.ToLower(tt.name))
		})
	}
}

func TestIsSensitiveHeader(t *testing.T) {
	tests := []struct {
		name string
		want matches
	}{
		{"token", whole ^ atEnd},
		{"password", allMatches},
		{"secret", allMatches},
		{"key", whole ^ atEnd},
		{"signature", allMatches},
		{"authorization", whole},
		{"name", noMatches},
		{"gitlab", noMatches},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			check := func(v string) {
				gotWhole := IsSensitiveHeader(v)
				require.Equal(t, tt.want&whole != 0, gotWhole, "Whole param match on '%s'", v)

				gotMiddle := IsSensitiveHeader("prefix" + v + "suffix")
				require.Equal(t, tt.want&inMiddle != 0, gotMiddle, "Middle match on '%s'", "prefix"+v+"suffix")

				gotStart := IsSensitiveHeader(v + "suffix")
				require.Equal(t, tt.want&atStart != 0, gotStart, "Start match on '%s'", v+"suffix")

				gotEnd := IsSensitiveHeader("prefix" + v)
				require.Equal(t, tt.want&atEnd != 0, gotEnd, "End match on '%s'", "prefix"+v)
			}

			check(tt.name)
			check(strings.ToUpper(tt.name))
			check(strings.ToLower(tt.name))
		})
	}
}
