package handlers

import (
	"testing"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestGenerateJWTWithAllClaims_UniqueTokens(t *testing.T) {
	handler := &AuthHandler{jwtKey: []byte("test-secret-key")}

	token1, err := handler.generateJWTWithAllClaims("user-id-1", "admin", "test@test.com", "testuser")
	require.NoError(t, err)
	assert.NotEmpty(t, token1)

	token2, err := handler.generateJWTWithAllClaims("user-id-1", "admin", "test@test.com", "testuser")
	require.NoError(t, err)
	assert.NotEmpty(t, token2)

	assert.NotEqual(t, token1, token2, "Tokens generated at same time should be different due to jti")
}

func TestGenerateJWTWithAllClaims_ValidClaims(t *testing.T) {
	handler := &AuthHandler{jwtKey: []byte("test-secret-key")}

	token, err := handler.generateJWTWithAllClaims("user-id-123", "admin", "admin@test.com", "adminuser")
	require.NoError(t, err)
	assert.NotEmpty(t, token)

	parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return []byte("test-secret-key"), nil
	})
	require.NoError(t, err)

	claims := parsedToken.Claims.(jwt.MapClaims)
	assert.Equal(t, "user-id-123", claims["user_id"])
	assert.Equal(t, "admin", claims["user_role"])
	assert.Equal(t, "admin@test.com", claims["user_email"])
	assert.Equal(t, "adminuser", claims["user_username"])
	assert.Contains(t, claims, "jti")
	assert.Contains(t, claims, "exp")
	assert.Contains(t, claims, "iat")

	exp := int64(claims["exp"].(float64))
	iat := int64(claims["iat"].(float64))
	assert.Greater(t, exp, iat, "exp should be greater than iat")
	assert.Greater(t, exp, time.Now().Unix(), "exp should be in the future")
}

func TestGenerateJWTWithRole(t *testing.T) {
	handler := &AuthHandler{jwtKey: []byte("test-secret-key")}

	token, err := handler.generateJWTWithRole("user-id-456", "moderator")
	require.NoError(t, err)
	assert.NotEmpty(t, token)

	parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return []byte("test-secret-key"), nil
	})
	require.NoError(t, err)

	claims := parsedToken.Claims.(jwt.MapClaims)
	assert.Equal(t, "user-id-456", claims["user_id"])
	assert.Equal(t, "moderator", claims["user_role"])
	assert.Equal(t, "", claims["user_email"])
	assert.Equal(t, "", claims["user_username"])
}

func TestGenerateJWT(t *testing.T) {
	handler := &AuthHandler{jwtKey: []byte("test-secret-key")}

	token, err := handler.generateJWT("user-id-789")
	require.NoError(t, err)
	assert.NotEmpty(t, token)

	parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return []byte("test-secret-key"), nil
	})
	require.NoError(t, err)

	claims := parsedToken.Claims.(jwt.MapClaims)
	assert.Equal(t, "user-id-789", claims["user_id"])
	assert.Equal(t, "user", claims["user_role"])
}
