package accounts

import "testing"

func TestGenerateTokensIncludesRoleClaim(t *testing.T) {
	t.Setenv("JWT_SECRET", "test-access-secret")
	t.Setenv("JWT_REFRESH_SECRET", "test-refresh-secret")

	accessToken, refreshToken, err := GenerateTokens(42, RoleAdmin)
	if err != nil {
		t.Fatalf("GenerateTokens returned error: %v", err)
	}

	accessClaims, err := parseAccessClaims(accessToken)
	if err != nil {
		t.Fatalf("parseAccessClaims returned error: %v", err)
	}

	if accessClaims.UserID != 42 {
		t.Fatalf("expected access user id 42, got %d", accessClaims.UserID)
	}

	if accessClaims.Role != RoleAdmin {
		t.Fatalf("expected access role %q, got %q", RoleAdmin, accessClaims.Role)
	}

	refreshUserID, err := ParseRefreshToken(refreshToken)
	if err != nil {
		t.Fatalf("ParseRefreshToken returned error: %v", err)
	}

	if refreshUserID != 42 {
		t.Fatalf("expected refresh user id 42, got %d", refreshUserID)
	}
}

func TestGenerateTokensNormalizesUnknownRoleToUser(t *testing.T) {
	t.Setenv("JWT_SECRET", "test-access-secret")
	t.Setenv("JWT_REFRESH_SECRET", "test-refresh-secret")

	accessToken, _, err := GenerateTokens(7, "superuser")
	if err != nil {
		t.Fatalf("GenerateTokens returned error: %v", err)
	}

	accessClaims, err := parseAccessClaims(accessToken)
	if err != nil {
		t.Fatalf("parseAccessClaims returned error: %v", err)
	}

	if accessClaims.Role != RoleUser {
		t.Fatalf("expected normalized role %q, got %q", RoleUser, accessClaims.Role)
	}
}
