package auxjwt

import (
	"testing"
	"time"

	"github.com/stretchr/testify/require"
)

func TestJWTGood(t *testing.T) {
	const issuer = "Issuer"
	const subject = "Subject"
	const lifetime = 10 * time.Second
	secret := []byte("12345")
	var sessionId int64 = 123456789

	var err error
	tokenBytes, _, err := MakeJWTToken(issuer, subject, sessionId, lifetime, secret)
	require.NoError(t, err)
	require.NotNil(t, tokenBytes)

	recvSessionID, err := GetJWTSessionID(tokenBytes, secret)
	require.NoError(t, err)
	require.Equal(t, sessionId, recvSessionID)

	err = ValidateJWTToken(tokenBytes, issuer, subject, secret)
	require.NoError(t, err)
}

func TestJWTTimeExpired(t *testing.T) {

	const issuer = "Issuer"
	const subject = "Subject"
	const lifetime = 1 * time.Second
	secret := []byte("12345")
	var sessionId int64 = 123456789

	var err error
	tokenBytes, _, err := MakeJWTToken(issuer, subject, sessionId, lifetime, secret)
	require.NoError(t, err)
	require.NotNil(t, tokenBytes)

	time.Sleep(2 * time.Second)

	err = ValidateJWTToken(tokenBytes, issuer, subject, secret)
	require.Error(t, err)
}

func TestJWTWrongSecret(t *testing.T) {

	const issuer = "Issuer"
	const subject = "Subject"
	const lifetime = 10 * time.Second
	secret := []byte("12345")
	var sessionId int64 = 123456789

	var err error
	tokenBytes, _, err := MakeJWTToken(issuer, subject, sessionId, lifetime, secret)
	require.NoError(t, err)
	require.NotNil(t, tokenBytes)

	secret = []byte("12345+1")
	err = ValidateJWTToken(tokenBytes, issuer, subject, secret)
	require.Error(t, err)
}

func TestJWTWrongIssuer(t *testing.T) {
	var issuer = "Issuer"
	const subject = "Subject"
	const lifetime = 10 * time.Second
	secret := []byte("12345")
	var sessionId int64 = 123456789

	var err error
	tokenBytes, _, err := MakeJWTToken(issuer, subject, sessionId, lifetime, secret)
	require.NoError(t, err)
	require.NotNil(t, tokenBytes)

	issuer = "mr.santa"
	err = ValidateJWTToken(tokenBytes, issuer, subject, secret)
	require.Error(t, err)
}

func TestJWTWrongSubject(t *testing.T) {
	const issuer = "Issuer"
	var subject = "Subject"
	const lifetime = 10 * time.Second
	secret := []byte("12345")
	var sessionId int64 = 123456789

	var err error
	tokenBytes, _, err := MakeJWTToken(issuer, subject, sessionId, lifetime, secret)
	require.NoError(t, err)
	require.NotNil(t, tokenBytes)

	subject = "$$$"

	err = ValidateJWTToken(tokenBytes, issuer, subject, secret)
	require.Error(t, err)
}
