package rbac

import (
	"reflect"
	"testing"
	"time"

	"github.com/golang-jwt/jwt"
)

func TestJWTManager_GenerateToken(t *testing.T) {
	type fields struct {
		secretKey     string
		tokenDuration time.Duration
	}
	type args struct {
		user User
	}
	tests := []struct {
		name    string
		fields  fields
		args    args
		want    string
		wantErr bool
	}{
		{
			name: "default generate token",
			fields: fields{
				secretKey:     "",
				tokenDuration: 1 * time.Minute,
			},
			args: args{
				user: User{
					UserName: "testUser",
				},
			},
			want:    "testUser",
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			man := &JWTManager{
				secretKey:     tt.fields.secretKey,
				tokenDuration: tt.fields.tokenDuration,
			}
			got, err := man.GenerateToken(tt.args.user)
			if (err != nil) != tt.wantErr {
				t.Errorf("JWTManager.GenerateToken() error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			gotClaims, _ := man.VerifyToken(got)
			claimsUser := gotClaims.Username

			if claimsUser != tt.want {
				t.Errorf("JWTManager.GenerateToken() = %v, want %v", claimsUser, tt.want)
			}
		})
	}
}

func TestJWTManager_VerifyToken(t *testing.T) {
	type fields struct {
		secretKey     string
		tokenDuration time.Duration
	}
	tests := []struct {
		name     string
		fields   fields
		userName string
		want     *UserClaims
		wantErr  bool
	}{
		{
			name: "default verify token",
			fields: fields{
				secretKey:     "",
				tokenDuration: 1 * time.Minute,
			},
			userName: "testUser",
			want: &UserClaims{
				StandardClaims: jwt.StandardClaims{
					ExpiresAt: time.Now().Add(1 * time.Minute).Unix(),
				},
				Username: "testUser",
			},
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			man := &JWTManager{
				secretKey:     tt.fields.secretKey,
				tokenDuration: tt.fields.tokenDuration,
			}

			token, _ := man.GenerateToken(User{UserName: tt.userName})
			got, err := man.VerifyToken(token)
			if (err != nil) != tt.wantErr {
				t.Errorf("JWTManager.VerifyToken() error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("JWTManager.VerifyToken() = %v, want %v", got, tt.want)
			}
		})
	}
}
