package api

import (
	"context"
	"testing"

	apb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/rbac"
	log "github.com/sirupsen/logrus"
	"google.golang.org/grpc/metadata"
)

func TestLogin(t *testing.T) {
	type args struct {
		ctx      context.Context
		addr     string
		username string
		pwd      string
	}
	tests := []struct {
		name    string
		args    args
		want    *apb.LoginResponse
		wantErr bool
	}{
		{
			name: "default",
			args: args{
				ctx:      context.TODO(),
				addr:     testAPIEndpoint,
				username: "testAdmin",
				pwd:      "admin",
			},
			want: &apb.LoginResponse{
				Status: apb.Status_STATUS_OK,
			},
			wantErr: false,
		},
		{
			name: "wrong login credentials",
			args: args{
				ctx:      context.TODO(),
				addr:     testAPIEndpoint,
				username: "testAdmin",
				pwd:      "nope",
			},
			want:    nil,
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := Login(tt.args.ctx, tt.args.addr, tt.args.username, tt.args.pwd)
			if (err != nil) != tt.wantErr {
				t.Errorf("Login() error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			if got != nil {
				if got.Status != apb.Status_STATUS_OK || got.Token == "" {
					t.Errorf("Auth.Login() = %v, want non empty token", got)
				}
			}
		})
	}
}

func TestLogout(t *testing.T) {
	validToken, err := createTestUserToken("testAdmin", true)
	if err != nil {
		log.Fatal(err)
	}

	type args struct {
		ctx      context.Context
		addr     string
		username string
	}
	tests := []struct {
		name    string
		args    args
		want    *apb.LogoutResponse
		wantErr bool
	}{
		{
			name: "default log out",
			args: args{
				ctx:      metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorize", validToken)),
				addr:     testAPIEndpoint,
				username: "testAdmin",
			},
			want: &apb.LogoutResponse{
				Status: apb.Status_STATUS_OK,
			},
			wantErr: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := Logout(tt.args.ctx, tt.args.addr, tt.args.username)
			if (err != nil) != tt.wantErr {
				t.Errorf("Logout() error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			if got != nil && got.Status != tt.want.Status {
				t.Errorf("Role.CreateRoles() = %v, want %v", got, tt.want)
			}
		})
	}
}
