from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user
from app.email_processor import EmailProcessor

decorators = [login_required]

bp = Blueprint('background_processing', __name__, url_prefix='/api/background')

@bp.route('/process-emails', methods=['POST'])
def trigger_email_processing():
    """
    Trigger immediate email processing for the current user.
    """
    try:
        processor = EmailProcessor(current_user)
        result = processor.process_user_emails()
        
        return jsonify({
            'success': True,
            'message': f"Processed {result['success_count']} emails successfully",
            'details': result
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@bp.route('/process-folder/<int:folder_id>', methods=['POST'])
def trigger_folder_processing(folder_id):
    """
    Trigger email processing for a specific folder.
    """
    try:
        # Verify the folder belongs to the current user
        from app.models import Folder
        folder = Folder.query.filter_by(id=folder_id, user_id=current_user.id).first()
        
        if not folder:
            return jsonify({
                'success': False,
                'error': 'Folder not found or access denied'
            }), 404
        
        processor = EmailProcessor(current_user)
        result = processor.process_folder_emails(folder)
        
        return jsonify({
            'success': True,
            'message': f"Processed {result['processed_count']} emails for folder {folder.name}",
            'details': result
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500