package routes

import (
	"net/http"
	"testing"

	"bitbucket.org/imediabrands/oos-service/middlewares"
)

func TestGaScriptSrc(t *testing.T) {
	tests := []struct {
		name  string
		gaId  string
		gaCx  string
		gaGtm string
		want  string
	}{
		{
			name: "measurement id only",
			gaId: "G-E3RLYFEDPQ",
			want: "https://www.googletagmanager.com/gtag/js?id=G-E3RLYFEDPQ",
		},
		{
			name:  "with cx and gtm",
			gaId:  "G-G8P90J51Q4",
			gaCx:  "c",
			gaGtm: "4e66g1h1",
			want:  "https://www.googletagmanager.com/gtag/js?id=G-G8P90J51Q4&cx=c&gtm=4e66g1h1",
		},
		{
			name: "cx only",
			gaId: "G-WLC33MNKYE",
			gaCx: "c",
			want: "https://www.googletagmanager.com/gtag/js?id=G-WLC33MNKYE&cx=c",
		},
		{
			name: "empty",
			gaId: "",
			want: "",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := gaScriptSrc(tt.gaId, tt.gaCx, tt.gaGtm)
			if string(got) != tt.want {
				t.Fatalf("gaScriptSrc() = %q, want %q", got, tt.want)
			}
		})
	}
}

func TestGaSettingsFromConfig(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"ga_id": "G-G8P90J51Q4",
		"ga_cx": "c",
		"ga_gtm": "4e66g1h1",
		"gtm_id": "GTM-T9B9RFC",
		"google_csa": true
	}`, &http.Request{})
	got := gaSettingsFromConfig(middlewares.GetClientConfig(req.Context()))
	if got.GaId != "G-G8P90J51Q4" || got.GaCx != "c" || got.GaGtm != "4e66g1h1" {
		t.Fatalf("unexpected settings: %+v", got)
	}
	if got.GtmId != "GTM-T9B9RFC" || !got.GoogleCsa {
		t.Fatalf("unexpected gtm/csa settings: %+v", got)
	}
}

func TestSanitizeGtmID(t *testing.T) {
	tests := []struct {
		in   string
		want string
	}{
		{"GTM-T9B9RFC", "GTM-T9B9RFC"},
		{"  GTM-T9B9RFC  ", "GTM-T9B9RFC"},
		{"gtm-t9b9rfc", ""},
		{"GTM-T9B9RFC';alert(1)", ""},
		{"", ""},
	}
	for _, tt := range tests {
		if got := sanitizeGtmID(tt.in); got != tt.want {
			t.Fatalf("sanitizeGtmID(%q) = %q, want %q", tt.in, got, tt.want)
		}
	}
}
