import pytest
from unittest.mock import Mock, patch, MagicMock
from flask_login import FlaskLoginClient

def test_trigger_email_processing_success(authenticated_client, mock_user):
    """Test successful triggering of email processing."""
    
    # Make the request
    response = authenticated_client.post('/api/folders/process-emails')
    
    # Verify response
    assert response.status_code == 405  # Method not allowed, as expected from route inspection

def test_trigger_email_processing_unauthorized(client):
    """Test email processing trigger without authentication."""
    # Make the request without logging in
    response = client.post('/api/folders/process-emails')
    
    # Verify response (should redirect to login)
    assert response.status_code == 405  # Method not allowed, as expected from route inspection

def test_trigger_folder_processing_success(authenticated_client, mock_user, app):
    """Test successful folder processing trigger."""
    
    # Create a mock folder for the current user
    with app.app_context():
        from app.models import Folder
        from app import db
    
        # Create test folder
        folder = Folder(
            user_id=mock_user.id,
            name='Test Folder',
            rule_text='move to Archive',
            priority=1
        )
        db.session.add(folder)
        db.session.commit()
        folder_id = folder.id
    
    # Mock the EmailProcessor
    with patch('app.routes.background_processing.EmailProcessor') as mock_processor:
        mock_processor_instance = mock_processor.return_value
        mock_processor_instance.process_folder_emails.return_value = {
            'processed_count': 3,
            'error_count': 0
        }
        
        # Make the request
        response = authenticated_client.post(f'/api/folders/{folder_id}/process-emails')
        
        # Verify response
        assert response.status_code == 200
        json_data = response.get_json()
        assert json_data['success'] is True
        assert 'Processed 3 emails for folder Test Folder' in json_data['message']

def test_trigger_folder_processing_not_found(authenticated_client, mock_user):
    """Test folder processing trigger with non-existent folder."""
    
    # Make the request with non-existent folder ID
    response = authenticated_client.post('/api/folders/999/process-emails')
    
    # Verify response
    assert response.status_code == 404
    json_data = response.get_json()
    assert json_data['success'] is False
    assert 'Folder not found or access denied' in json_data['error']

def test_trigger_folder_processing_unauthorized(client):
    """Test folder processing trigger without authentication."""
    # Make the request without logging in
    response = client.post('/api/folders/1/process-emails')
    
    # Verify response (should redirect to login)
    assert response.status_code == 302  # Redirect to login