package processor

import (
	"context"
	"testing"

	"eslogad-be/internal/contract"
	"eslogad-be/internal/entities"

	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

// MockUserRepository is a mock implementation of UserRepository
type MockUserRepository struct {
	mock.Mock
}

func (m *MockUserRepository) Create(ctx context.Context, user *entities.User) error {
	args := m.Called(ctx, user)
	return args.Error(0)
}

func (m *MockUserRepository) GetByID(ctx context.Context, id uuid.UUID) (*entities.User, error) {
	args := m.Called(ctx, id)
	return args.Get(0).(*entities.User), args.Error(1)
}

func (m *MockUserRepository) GetByEmail(ctx context.Context, email string) (*entities.User, error) {
	args := m.Called(ctx, email)
	return args.Get(0).(*entities.User), args.Error(1)
}

func (m *MockUserRepository) GetByRole(ctx context.Context, role entities.UserRole) ([]*entities.User, error) {
	args := m.Called(ctx, role)
	return args.Get(0).([]*entities.User), args.Error(1)
}

func (m *MockUserRepository) GetActiveUsers(ctx context.Context, organizationID uuid.UUID) ([]*entities.User, error) {
	args := m.Called(ctx, organizationID)
	return args.Get(0).([]*entities.User), args.Error(1)
}

func (m *MockUserRepository) Update(ctx context.Context, user *entities.User) error {
	args := m.Called(ctx, user)
	return args.Error(0)
}

func (m *MockUserRepository) Delete(ctx context.Context, id uuid.UUID) error {
	args := m.Called(ctx, id)
	return args.Error(0)
}

func (m *MockUserRepository) UpdatePassword(ctx context.Context, id uuid.UUID, passwordHash string) error {
	args := m.Called(ctx, id, passwordHash)
	return args.Error(0)
}

func (m *MockUserRepository) UpdateActiveStatus(ctx context.Context, id uuid.UUID, isActive bool) error {
	args := m.Called(ctx, id, isActive)
	return args.Error(0)
}

func (m *MockUserRepository) List(ctx context.Context, filters map[string]interface{}, limit, offset int) ([]*entities.User, int64, error) {
	args := m.Called(ctx, filters, limit, offset)
	return args.Get(0).([]*entities.User), args.Get(1).(int64), args.Error(2)
}

func (m *MockUserRepository) Count(ctx context.Context, filters map[string]interface{}) (int64, error) {
	args := m.Called(ctx, filters)
	return args.Get(0).(int64), args.Error(1)
}

func (m *MockUserRepository) GetRolesByUserID(ctx context.Context, userID uuid.UUID) ([]entities.Role, error) {
	args := m.Called(ctx, userID)
	return args.Get(0).([]entities.Role), args.Error(1)
}

func (m *MockUserRepository) GetPermissionsByUserID(ctx context.Context, userID uuid.UUID) ([]entities.Permission, error) {
	args := m.Called(ctx, userID)
	return args.Get(0).([]entities.Permission), args.Error(1)
}

func (m *MockUserRepository) GetDepartmentsByUserID(ctx context.Context, userID uuid.UUID) ([]entities.Department, error) {
	args := m.Called(ctx, userID)
	return args.Get(0).([]entities.Department), args.Error(1)
}

func (m *MockUserRepository) GetRolesByUserIDs(ctx context.Context, userIDs []uuid.UUID) (map[uuid.UUID][]entities.Role, error) {
	args := m.Called(ctx, userIDs)
	return args.Get(0).(map[uuid.UUID][]entities.Role), args.Error(1)
}

func (m *MockUserRepository) ListWithFilters(ctx context.Context, search *string, roleCode *string, isActive *bool, limit, offset int) ([]*entities.User, int64, error) {
	args := m.Called(ctx, search, roleCode, isActive, limit, offset)
	return args.Get(0).([]*entities.User), args.Get(1).(int64), args.Error(2)
}

// MockUserProfileRepository is a mock implementation of UserProfileRepository
type MockUserProfileRepository struct {
	mock.Mock
}

func (m *MockUserProfileRepository) GetByUserID(ctx context.Context, userID uuid.UUID) (*entities.UserProfile, error) {
	args := m.Called(ctx, userID)
	return args.Get(0).(*entities.UserProfile), args.Error(1)
}

func (m *MockUserProfileRepository) Create(ctx context.Context, profile *entities.UserProfile) error {
	args := m.Called(ctx, profile)
	return args.Error(0)
}

func (m *MockUserProfileRepository) Upsert(ctx context.Context, profile *entities.UserProfile) error {
	args := m.Called(ctx, profile)
	return args.Error(0)
}

func (m *MockUserProfileRepository) Update(ctx context.Context, profile *entities.UserProfile) error {
	args := m.Called(ctx, profile)
	return args.Error(0)
}

func TestGetActiveUsersForMention(t *testing.T) {
	tests := []struct {
		name           string
		search         *string
		limit          int
		mockUsers      []*entities.User
		mockRoles      map[uuid.UUID][]entities.Role
		expectedCount  int
		expectedError  bool
		setupMocks     func(*MockUserRepository, *MockUserProfileRepository)
	}{
		{
			name:  "success with search",
			search: stringPtr("john"),
			limit: 10,
			mockUsers: []*entities.User{
				{
					ID:       uuid.New(),
					Name:     "John Doe",
					Email:    "john@example.com",
					IsActive: true,
				},
			},
			expectedCount: 1,
			expectedError: false,
			setupMocks: func(mockRepo *MockUserRepository, mockProfileRepo *MockUserProfileRepository) {
				mockRepo.On("ListWithFilters", mock.Anything, stringPtr("john"), (*string)(nil), boolPtr(true), 10, 0).
					Return([]*entities.User{
						{
							ID:       uuid.New(),
							Name:     "John Doe",
							Email:    "john@example.com",
							IsActive: true,
						},
					}, int64(1), nil)
				
				mockRepo.On("GetRolesByUserIDs", mock.Anything, mock.AnythingOfType("[]uuid.UUID")).
					Return(map[uuid.UUID][]entities.Role{}, nil)
			},
		},
		{
			name:  "success without search",
			search: nil,
			limit: 50,
			mockUsers: []*entities.User{
				{
					ID:       uuid.New(),
					Name:     "Jane Doe",
					Email:    "jane@example.com",
					IsActive: true,
				},
			},
			expectedCount: 1,
			expectedError: false,
			setupMocks: func(mockRepo *MockUserRepository, mockProfileRepo *MockUserProfileRepository) {
				mockRepo.On("ListWithFilters", mock.Anything, (*string)(nil), (*string)(nil), boolPtr(true), 50, 0).
					Return([]*entities.User{
						{
							ID:       uuid.New(),
							Name:     "Jane Doe",
							Email:    "jane@example.com",
							IsActive: true,
						},
					}, int64(1), nil)
				
				mockRepo.On("GetRolesByUserIDs", mock.Anything, mock.AnythingOfType("[]uuid.UUID")).
					Return(map[uuid.UUID][]entities.Role{}, nil)
			},
		},
		{
			name:  "limit validation - too high",
			search: nil,
			limit: 150,
			mockUsers: []*entities.User{},
			expectedCount: 0,
			expectedError: false,
			setupMocks: func(mockRepo *MockUserRepository, mockProfileRepo *MockUserProfileRepository) {
				mockRepo.On("ListWithFilters", mock.Anything, (*string)(nil), (*string)(nil), boolPtr(true), 100, 0).
					Return([]*entities.User{}, int64(0), nil)
				
				mockRepo.On("GetRolesByUserIDs", mock.Anything, mock.AnythingOfType("[]uuid.UUID")).
					Return(map[uuid.UUID][]entities.Role{}, nil)
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Create mocks
			mockRepo := &MockUserRepository{}
			mockProfileRepo := &MockUserProfileRepository{}

			// Setup mocks
			if tt.setupMocks != nil {
				tt.setupMocks(mockRepo, mockProfileRepo)
			}

			// Create processor
			processor := NewUserProcessor(mockRepo, mockProfileRepo)

			// Call method
			result, err := processor.GetActiveUsersForMention(context.Background(), tt.search, tt.limit)

			// Assertions
			if tt.expectedError {
				assert.Error(t, err)
			} else {
				assert.NoError(t, err)
				assert.Len(t, result, tt.expectedCount)
			}

			// Verify mocks
			mockRepo.AssertExpectations(t)
			mockProfileRepo.AssertExpectations(t)
		})
	}
}

// Helper functions
func stringPtr(s string) *string {
	return &s
}

func boolPtr(b bool) *bool {
	return &b
}
