package auth

import (
	"log"
	"testing"
	"time"

	"git.schreifuchs.ch/schreifuchs/ng-blog/internal/model"
	"github.com/google/uuid"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func testDB() (db *gorm.DB) {
	db, err := gorm.Open(sqlite.Open(":memory:"))
	if err != nil {
		log.Panic(err)
	}

	db.AutoMigrate(&model.User{}, &model.InvalidJWT{})

	return
}

func TestService_JWT(t *testing.T) {
	t.Parallel()
	tests := []struct {
		user model.User
	}{
		{
			user: model.User{
				ID:   0,
				Name: "Hans de Admin",
				Role: model.RoleAdmin,
				UUID: uuid.MustParse("9d8973b7-2005-4ca6-a4bf-7bae5aad2916"),
			},
		},
		{
			user: model.User{
				ID:   1,
				Name: "Ueli de User",
				Role: model.RoleUser,
				UUID: uuid.MustParse("e1b7099f-a3be-4d77-b33f-389e27123187"),
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.user.Name, func(t *testing.T) {
			t.Parallel()
			s := New(&Config{
				Secret:        "asdf",
				ValidDuration: time.Hour,
				AdminName:     "adsf",
				AdminPassword: "adsf",
			}, testDB())

			jwt, err := s.createJWT(&tt.user)
			if err != nil {
				t.Errorf("Error while creating JWT: %v", err)
			}

			claims, err := s.validateJWT(jwt)
			if err != nil {
				t.Errorf("Error while creating JWT: %v", err)
			}

			if claims.Subject != tt.user.UUID.String() {
				t.Error("Subject does not match")
			}
			if claims.Role != tt.user.Role {
				t.Error("Roles did not match")
			}
		})
	}
}
