package middleware

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"veza-backend-api/internal/models"
	"veza-backend-api/internal/services"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	"go.uber.org/zap"
)

// MockPermissionChecker pour les tests RBAC avec UUID
// GO-001, GO-005, GO-006: Tests pour RequireAdmin et RequirePermission
type MockPermissionChecker struct {
	mock.Mock
}

func (m *MockPermissionChecker) HasRole(ctx context.Context, userID uuid.UUID, roleName string) (bool, error) {
	args := m.Called(ctx, userID, roleName)
	return args.Bool(0), args.Error(1)
}

func (m *MockPermissionChecker) HasPermission(ctx context.Context, userID uuid.UUID, permissionName string) (bool, error) {
	args := m.Called(ctx, userID, permissionName)
	return args.Bool(0), args.Error(1)
}

// setupTestAuthMiddlewareWithRBAC crée un AuthMiddleware avec mock PermissionChecker
// Utilise la même approche que setupTestAuthMiddleware mais avec un PermissionChecker personnalisé
func setupTestAuthMiddlewareWithRBAC(t *testing.T, permissionChecker PermissionChecker) (*AuthMiddleware, *MockSessionService, *MockAuditService, *MockUserRepository) {
	logger, _ := zap.NewDevelopment()
	mockSessionService := new(MockSessionService)
	mockAuditService := new(MockAuditService)
	mockAuditService.On("LogAction", mock.Anything, mock.Anything).Return(nil).Maybe()

	// Mock User Repository (defined in auth_middleware_test.go)
	mockUserRepository := new(MockUserRepository)
	// Default behavior: return a user with token version 0
	mockUserRepository.On("GetByID", mock.Anything).Return(&models.User{
		ID:           uuid.New(),
		TokenVersion: 0,
	}, nil).Maybe()

	jwtService := setupTestJWTService(t) // Reuse helper from auth_middleware_test.go
	userService := services.NewUserService(mockUserRepository)

	authMiddleware := NewAuthMiddleware(mockSessionService, mockAuditService, permissionChecker, jwtService, userService, logger)

	return authMiddleware, mockSessionService, mockAuditService, mockUserRepository
}

// generateTestToken crée un token JWT compatible avec AuthMiddleware.validateJWTToken
func generateTestTokenForRBAC(t *testing.T, userID uuid.UUID, expiresIn time.Duration) string {
	claims := jwt.MapClaims{
		"sub":           userID.String(), // CustomClaims maps UserID to "sub"
		"exp":           time.Now().Add(expiresIn).Unix(),
		"iat":           time.Now().Unix(),
		"iss":           "veza-api",
		"aud":           "veza-app",
		"token_version": 0,
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte(testJWTSecret))
	require.NoError(t, err)
	return tokenString
}

// TestRequireAdmin_WithAdminRole teste que RequireAdmin accepte un utilisateur admin
// GO-001, GO-005, GO-006: Test RBAC RequireAdmin
func TestRequireAdmin_WithAdminRole(t *testing.T) {
	gin.SetMode(gin.TestMode)

	userID := uuid.New()
	mockPermissionChecker := new(MockPermissionChecker)
	mockPermissionChecker.On("HasRole", mock.Anything, userID, "admin").Return(true, nil)

	authMiddleware, mockSessionService, _, mockUserRepository := setupTestAuthMiddlewareWithRBAC(t, mockPermissionChecker)

	// Ensure UserRepo returns correct user
	mockUserRepository.ExpectedCalls = nil
	mockUserRepository.On("GetByID", userID.String()).Return(&models.User{
		ID:           userID,
		TokenVersion: 0,
	}, nil)

	// Générer un token JWT valide et mocker la session
	token := generateTestTokenForRBAC(t, userID, 15*time.Minute)
	sessionID := uuid.New()
	mockSession := &services.Session{
		ID:        sessionID,
		UserID:    userID,
		CreatedAt: time.Now(),
		ExpiresAt: time.Now().Add(24 * time.Hour),
	}
	mockSessionService.On("ValidateSession", mock.Anything, token).Return(mockSession, nil)

	router := gin.New()
	router.Use(authMiddleware.RequireAdmin())
	router.GET("/test", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "success"})
	})

	req := httptest.NewRequest(http.MethodGet, "/test", nil)
	req.Header.Set("Authorization", "Bearer "+token)
	w := httptest.NewRecorder()

	router.ServeHTTP(w, req)

	assert.Equal(t, http.StatusOK, w.Code)
	mockPermissionChecker.AssertExpectations(t)
	mockSessionService.AssertExpectations(t)
}

// TestRequireAdmin_WithNonAdminRole teste que RequireAdmin rejette un utilisateur non-admin
// GO-001, GO-005, GO-006: Test RBAC RequireAdmin
func TestRequireAdmin_WithNonAdminRole(t *testing.T) {
	gin.SetMode(gin.TestMode)

	userID := uuid.New()
	mockPermissionChecker := new(MockPermissionChecker)
	mockPermissionChecker.On("HasRole", mock.Anything, userID, "admin").Return(false, nil)

	authMiddleware, mockSessionService, _, mockUserRepository := setupTestAuthMiddlewareWithRBAC(t, mockPermissionChecker)

	// Ensure UserRepo returns correct user
	mockUserRepository.ExpectedCalls = nil
	mockUserRepository.On("GetByID", userID.String()).Return(&models.User{
		ID:           userID,
		TokenVersion: 0,
	}, nil)

	// Générer un token JWT valide et mocker la session
	token := generateTestTokenForRBAC(t, userID, 15*time.Minute)
	sessionID := uuid.New()
	mockSession := &services.Session{
		ID:        sessionID,
		UserID:    userID,
		CreatedAt: time.Now(),
		ExpiresAt: time.Now().Add(24 * time.Hour),
	}
	mockSessionService.On("ValidateSession", mock.Anything, token).Return(mockSession, nil)

	router := gin.New()
	router.Use(authMiddleware.RequireAdmin())
	router.GET("/test", func(c *gin.Context) {
		// Ne pas appeler c.JSON si le middleware a déjà répondu
		if !c.IsAborted() {
			c.JSON(http.StatusOK, gin.H{"message": "success"})
		}
	})

	req := httptest.NewRequest(http.MethodGet, "/test", nil)
	req.Header.Set("Authorization", "Bearer "+token)
	w := httptest.NewRecorder()

	router.ServeHTTP(w, req)

	// Le code de statut doit être 403 Forbidden
	assert.Equal(t, http.StatusForbidden, w.Code, "Non-admin user should be denied access")

	// Note: Gin peut appeler le handler même après c.Abort() dans certains cas,
	// mais le code de statut et le body final doivent refléter l'erreur du middleware
	bodyBytes := w.Body.Bytes()
	if len(bodyBytes) > 0 {
		// Chercher le dernier JSON dans le body (l'erreur du middleware)
		bodyStr := string(bodyBytes)
		lastJSONStart := -1
		for i := len(bodyStr) - 1; i >= 0; i-- {
			if bodyStr[i] == '{' {
				lastJSONStart = i
				break
			}
		}
		if lastJSONStart >= 0 {
			var response map[string]interface{}
			err := json.Unmarshal([]byte(bodyStr[lastJSONStart:]), &response)
			if err == nil && response["error"] != nil {
				// P0: Nouveau format AppError
				errorObj, ok := response["error"].(map[string]interface{})
				if ok {
					assert.Equal(t, "Insufficient permissions", errorObj["message"])
				}
			}
		}
	}

	mockPermissionChecker.AssertExpectations(t)
	mockSessionService.AssertExpectations(t)
}

// TestAuthMiddleware_RequirePermission_WithValidPermission teste que RequirePermission accepte avec permission valide
// GO-001, GO-005: Test RBAC RequirePermission
func TestAuthMiddleware_RequirePermission_WithValidPermission(t *testing.T) {
	gin.SetMode(gin.TestMode)

	userID := uuid.New()
	mockPermissionChecker := new(MockPermissionChecker)
	mockPermissionChecker.On("HasPermission", mock.Anything, userID, "tracks:create").Return(true, nil)

	authMiddleware, mockSessionService, _, mockUserRepository := setupTestAuthMiddlewareWithRBAC(t, mockPermissionChecker)

	mockUserRepository.ExpectedCalls = nil
	mockUserRepository.On("GetByID", userID.String()).Return(&models.User{
		ID:           userID,
		TokenVersion: 0,
	}, nil)

	// Mock session validation (RequirePermission appelle RequireAuth en interne)
	// Mock session validation (RequirePermission appelle RequireAuth en interne)
	token := generateTestTokenForRBAC(t, userID, 15*time.Minute)
	sessionID := uuid.New()
	mockSession := &services.Session{
		ID:        sessionID,
		UserID:    userID,
		CreatedAt: time.Now(),
		ExpiresAt: time.Now().Add(24 * time.Hour),
	}
	mockSessionService.On("ValidateSession", mock.Anything, token).Return(mockSession, nil)

	router := gin.New()
	router.Use(authMiddleware.RequirePermission("tracks:create"))
	router.POST("/test", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "success"})
	})

	req := httptest.NewRequest(http.MethodPost, "/test", nil)
	req.Header.Set("Authorization", "Bearer "+token)
	w := httptest.NewRecorder()

	router.ServeHTTP(w, req)

	assert.Equal(t, http.StatusOK, w.Code)
	mockPermissionChecker.AssertExpectations(t)
	mockSessionService.AssertExpectations(t)
}

// TestAuthMiddleware_RequirePermission_WithInvalidPermission teste que RequirePermission rejette sans permission
// GO-001, GO-005: Test RBAC RequirePermission
func TestAuthMiddleware_RequirePermission_WithInvalidPermission(t *testing.T) {
	gin.SetMode(gin.TestMode)

	userID := uuid.New()
	mockPermissionChecker := new(MockPermissionChecker)
	mockPermissionChecker.On("HasPermission", mock.Anything, userID, "tracks:delete").Return(false, nil)

	authMiddleware, mockSessionService, _, mockUserRepository := setupTestAuthMiddlewareWithRBAC(t, mockPermissionChecker)

	mockUserRepository.ExpectedCalls = nil
	mockUserRepository.On("GetByID", userID.String()).Return(&models.User{
		ID:           userID,
		TokenVersion: 0,
	}, nil)

	// Mock session validation (RequirePermission appelle RequireAuth en interne)
	token := generateTestTokenForRBAC(t, userID, 15*time.Minute)
	sessionID := uuid.New()
	mockSession := &services.Session{
		ID:        sessionID,
		UserID:    userID,
		CreatedAt: time.Now(),
		ExpiresAt: time.Now().Add(24 * time.Hour),
	}
	mockSessionService.On("ValidateSession", mock.Anything, token).Return(mockSession, nil)

	handlerCalled := false
	router := gin.New()
	router.Use(authMiddleware.RequirePermission("tracks:delete"))
	router.DELETE("/test", func(c *gin.Context) {
		handlerCalled = true
		c.JSON(http.StatusOK, gin.H{"message": "success"})
	})

	req := httptest.NewRequest(http.MethodDelete, "/test", nil)
	req.Header.Set("Authorization", "Bearer "+token)
	w := httptest.NewRecorder()

	router.ServeHTTP(w, req)

	assert.Equal(t, http.StatusForbidden, w.Code)
	assert.False(t, handlerCalled, "Handler should not be called without permission")

	var response map[string]interface{}
	err := json.Unmarshal(w.Body.Bytes(), &response)
	assert.NoError(t, err)
	// P0: Nouveau format AppError
	errorObj, ok := response["error"].(map[string]interface{})
	require.True(t, ok, "Error should be a map")
	assert.Equal(t, "Insufficient permissions", errorObj["message"])

	mockPermissionChecker.AssertExpectations(t)
	mockSessionService.AssertExpectations(t)
}

// TestRequireContentCreatorRole_WithCreatorRole teste que RequireContentCreatorRole accepte creator/premium/admin
// GO-012: Test middleware RequireContentCreatorRole
func TestRequireContentCreatorRole_WithCreatorRole(t *testing.T) {
	gin.SetMode(gin.TestMode)

	testCases := []struct {
		name     string
		roleName string
	}{
		{"Creator role", "creator"},
		{"Premium role", "premium"},
		{"Admin role", "admin"},
		{"Artist role", "artist"},
		{"Producer role", "producer"},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			userID := uuid.New()
			mockPermissionChecker := new(MockPermissionChecker)
			// Le middleware vérifie plusieurs rôles, on mock le rôle testé
			allowedRoles := []string{"creator", "premium", "admin", "artist", "producer", "label"}
			for _, r := range allowedRoles {
				shouldHave := (r == tc.roleName)
				mockPermissionChecker.On("HasRole", mock.Anything, userID, r).Return(shouldHave, nil).Maybe()
			}

			authMiddleware, mockSessionService, _, mockUserRepository := setupTestAuthMiddlewareWithRBAC(t, mockPermissionChecker)

			mockUserRepository.ExpectedCalls = nil
			mockUserRepository.On("GetByID", userID.String()).Return(&models.User{
				ID:           userID,
				TokenVersion: 0,
			}, nil)

			// Mock session validation (RequireContentCreatorRole appelle RequireAuth en interne)
			token := generateTestTokenForRBAC(t, userID, 15*time.Minute)
			sessionID := uuid.New()
			mockSession := &services.Session{
				ID:        sessionID,
				UserID:    userID,
				CreatedAt: time.Now(),
				ExpiresAt: time.Now().Add(24 * time.Hour),
			}
			mockSessionService.On("ValidateSession", mock.Anything, token).Return(mockSession, nil)

			router := gin.New()
			router.Use(authMiddleware.RequireContentCreatorRole())
			router.POST("/test", func(c *gin.Context) {
				c.JSON(http.StatusOK, gin.H{"message": "success"})
			})

			req := httptest.NewRequest(http.MethodPost, "/test", nil)
			req.Header.Set("Authorization", "Bearer "+token)
			w := httptest.NewRecorder()

			router.ServeHTTP(w, req)

			assert.Equal(t, http.StatusOK, w.Code, "Should allow %s role", tc.roleName)
			mockPermissionChecker.AssertExpectations(t)
			mockSessionService.AssertExpectations(t)
		})
	}
}

// TestRequireContentCreatorRole_WithUserRole teste que RequireContentCreatorRole rejette user standard
// GO-012: Test middleware RequireContentCreatorRole
func TestRequireContentCreatorRole_WithUserRole(t *testing.T) {
	gin.SetMode(gin.TestMode)

	userID := uuid.New()
	mockPermissionChecker := new(MockPermissionChecker)
	// Mock tous les rôles autorisés comme false (user standard n'a aucun de ces rôles)
	allowedRoles := []string{"creator", "premium", "admin", "artist", "producer", "label"}
	for _, role := range allowedRoles {
		mockPermissionChecker.On("HasRole", mock.Anything, userID, role).Return(false, nil).Maybe()
	}

	authMiddleware, mockSessionService, _, mockUserRepository := setupTestAuthMiddlewareWithRBAC(t, mockPermissionChecker)

	mockUserRepository.ExpectedCalls = nil
	mockUserRepository.On("GetByID", userID.String()).Return(&models.User{
		ID:           userID,
		TokenVersion: 0,
	}, nil)

	// Mock session validation (RequireContentCreatorRole appelle RequireAuth en interne)
	token := generateTestTokenForRBAC(t, userID, 15*time.Minute)
	sessionID := uuid.New()
	mockSession := &services.Session{
		ID:        sessionID,
		UserID:    userID,
		CreatedAt: time.Now(),
		ExpiresAt: time.Now().Add(24 * time.Hour),
	}
	mockSessionService.On("ValidateSession", mock.Anything, token).Return(mockSession, nil)

	handlerCalled := false
	router := gin.New()
	router.Use(authMiddleware.RequireContentCreatorRole())
	router.POST("/test", func(c *gin.Context) {
		handlerCalled = true
		c.JSON(http.StatusOK, gin.H{"message": "success"})
	})

	req := httptest.NewRequest(http.MethodPost, "/test", nil)
	req.Header.Set("Authorization", "Bearer "+token)
	w := httptest.NewRecorder()

	router.ServeHTTP(w, req)

	assert.Equal(t, http.StatusForbidden, w.Code)
	assert.False(t, handlerCalled, "Handler should not be called for standard user")

	var response map[string]interface{}
	err := json.Unmarshal(w.Body.Bytes(), &response)
	assert.NoError(t, err)
	assert.Contains(t, response, "error")
	// P0: Nouveau format AppError
	errorObj, ok := response["error"].(map[string]interface{})
	require.True(t, ok, "Error should be a map")
	assert.Contains(t, errorObj["message"].(string), "Insufficient permissions")

	mockPermissionChecker.AssertExpectations(t)
	mockSessionService.AssertExpectations(t)
}
