package vkauth_test

import (
	"errors"
	"net/url"
	"testing"

	"scrabble/gateway/internal/vkauth"
)

const (
	testSecret = "wv527nm6mvf3rgomfhd6"
	// goldenSign is HMAC-SHA256(sorted vk_* query, testSecret) base64url without
	// padding, computed independently from a Python reference over goldenParams — so a
	// green test proves Verify matches VK's documented algorithm, not merely itself.
	goldenSign = "x7RUe9sKN05Bigm-pBIl8gLmfMwZCloPrwZaZEQAdOA"
)

// goldenParams is the canonical VK launch-parameter set the golden signature covers
// (a representative real launch, including the empty vk_access_token_settings).
func goldenParams() url.Values {
	return url.Values{
		"vk_access_token_settings":     {""},
		"vk_app_id":                    {"6736218"},
		"vk_are_notifications_enabled": {"0"},
		"vk_is_app_user":               {"1"},
		"vk_is_favorite":               {"0"},
		"vk_language":                  {"ru"},
		"vk_platform":                  {"android"},
		"vk_ref":                       {"other"},
		"vk_ts":                        {"1546961916"},
		"vk_user_id":                   {"494075"},
	}
}

func signedParams() url.Values {
	p := goldenParams()
	p.Set("sign", goldenSign)
	return p
}

func TestVerifyValid(t *testing.T) {
	id, err := vkauth.Verify(signedParams().Encode(), testSecret)
	if err != nil {
		t.Fatalf("Verify: unexpected error %v", err)
	}
	if id.ExternalID != "494075" || id.Language != "ru" {
		t.Fatalf("identity = %+v, want ExternalID=494075 Language=ru", id)
	}
	if id.Platform != "android" || id.Subtype() != "android" {
		t.Fatalf("platform = %q subtype = %q, want android/android", id.Platform, id.Subtype())
	}
}

// TestSubtype locks the vk_platform -> device-family mapping (the trusted subtype),
// notably that iPhone and iPad both surface as the store-frozen "ios" and that any
// unrecognised or empty value falls back to web.
func TestSubtype(t *testing.T) {
	for _, tc := range []struct {
		platform string
		want     string
	}{
		{"mobile_iphone", "ios"},
		{"mobile_ipad", "ios"},
		{"mobile_iphone_messenger", "ios"},
		{"mobile_android", "android"},
		{"android", "android"},
		{"desktop_web", "web"},
		{"mobile_web", "web"},
		{"", "web"},
		{"something_new", "web"},
	} {
		if got := (vkauth.Identity{Platform: tc.platform}).Subtype(); got != tc.want {
			t.Errorf("Subtype(%q) = %q, want %q", tc.platform, got, tc.want)
		}
	}
}

// TestVerifyCommaValue locks the URL-encoding of the one realistic special-char VK
// value: vk_access_token_settings can carry a comma (e.g. "email,phone"), which VK's
// signer and our url.Values.Encode both escape to %2C. The golden sign was computed
// independently (Node crypto) over these params under testSecret — so a green test
// proves Go's encoding matches VK's for that character.
func TestVerifyCommaValue(t *testing.T) {
	p := url.Values{
		"vk_access_token_settings": {"email,phone"},
		"vk_app_id":                {"6736218"},
		"vk_language":              {"ru"},
		"vk_platform":              {"mobile_web"},
		"vk_ts":                    {"1546961916"},
		"vk_user_id":               {"494075"},
		"sign":                     {"6g9FKCAfHfT-fBUdBAcJ5QK1xUm-vKMvGZrQ63aPgnQ"},
	}
	id, err := vkauth.Verify(p.Encode(), testSecret)
	if err != nil {
		t.Fatalf("Verify: unexpected error %v", err)
	}
	if id.ExternalID != "494075" {
		t.Fatalf("ExternalID = %q, want 494075", id.ExternalID)
	}
}

// TestVerifyIgnoresForeignParams asserts a non-vk_ query parameter the client may
// append (e.g. a tracking tag) is outside the signed set and does not break the check.
func TestVerifyIgnoresForeignParams(t *testing.T) {
	id, err := vkauth.Verify(signedParams().Encode()+"&utm_source=catalog", testSecret)
	if err != nil {
		t.Fatalf("Verify: unexpected error %v", err)
	}
	if id.ExternalID != "494075" {
		t.Fatalf("ExternalID = %q, want 494075", id.ExternalID)
	}
}

func TestVerifyRejects(t *testing.T) {
	tests := []struct {
		name   string
		raw    string
		secret string
	}{
		{name: "tampered param", secret: testSecret, raw: func() string {
			p := signedParams()
			p.Set("vk_user_id", "1") // user id changed; the golden sign no longer matches
			return p.Encode()
		}()},
		{name: "wrong secret", secret: "not-the-secret", raw: signedParams().Encode()},
		{name: "missing sign", secret: testSecret, raw: goldenParams().Encode()},
		{name: "no vk params", secret: testSecret, raw: url.Values{"sign": {goldenSign}, "foo": {"bar"}}.Encode()},
		{name: "malformed query", secret: testSecret, raw: "%zz=bad"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if _, err := vkauth.Verify(tt.raw, tt.secret); !errors.Is(err, vkauth.ErrInvalid) {
				t.Fatalf("Verify error = %v, want ErrInvalid", err)
			}
		})
	}
}
