package services

import (
	"github.com/google/uuid"
	"testing"

	"github.com/stretchr/testify/assert"
	"veza-backend-api/internal/models"
)

func TestJWTService(t *testing.T) {
	secret := "test-secret-key-for-unit-tests-very-secure"
	jwtService := NewJWTService(secret)

	// Mock User
	// GO-004: Utiliser UUID au lieu de int
	userID := uuid.New()
	user := &models.User{
		ID:           userID,
		Email:        "test@example.com",
		Username:     "testuser",
		Role:         "user",
		TokenVersion: 5,
	}

	t.Run("GenerateAccessToken", func(t *testing.T) {
		token, err := jwtService.GenerateAccessToken(user)
		assert.NoError(t, err)
		assert.NotEmpty(t, token)

		// Validate immediately
		claims, err := jwtService.ValidateToken(token)
		assert.NoError(t, err)
		assert.Equal(t, user.ID, claims.UserID)
		assert.Equal(t, user.Email, claims.Email)
		assert.Equal(t, user.Role, claims.Role)
	})

	t.Run("GenerateRefreshToken", func(t *testing.T) {
		token, err := jwtService.GenerateRefreshToken(user)
		assert.NoError(t, err)
		assert.NotEmpty(t, token)

		// Validate
		claims, err := jwtService.ValidateToken(token)
		assert.NoError(t, err)
		assert.Equal(t, user.ID, claims.UserID)
		// Refresh token doesn't have email in current implementation
		assert.Empty(t, claims.Email)
	})

	t.Run("VerifyTokenVersion", func(t *testing.T) {
		// Generate token with user.TokenVersion = 5
		token, _ := jwtService.GenerateAccessToken(user)
		claims, _ := jwtService.ValidateToken(token)

		// Case 1: Same version -> OK
		err := jwtService.VerifyTokenVersion(claims, 5)
		assert.NoError(t, err)

		// Case 2: DB version is higher -> Error
		err = jwtService.VerifyTokenVersion(claims, 6)
		assert.Error(t, err)
		assert.Contains(t, err.Error(), "token version mismatch")

		// Case 3: DB version is lower -> OK (assuming implementation allows older tokens if logic permits, but usually equality is checked.
		// Let's check implementation logic: return claims.TokenVersion != currentVersion
		err = jwtService.VerifyTokenVersion(claims, 4)
		assert.Error(t, err) // Expect error because version must match
	})

	t.Run("ExpiredToken", func(t *testing.T) {
		// Manually create an expired token is hard without exposing internal methods or mocking time.
		// However, we can rely on the library validation tested above.
		// Ideally, we'd inject a TimeProvider into JWTService to test expiration.
		// For now, we trust the library and just check invalid signatures.

		invalidToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.invalid_signature"
		_, err := jwtService.ValidateToken(invalidToken)
		assert.Error(t, err)
	})
}
