"""Blueprint for background task management (Celery)."""

from flask import Blueprint, jsonify, request
from middleware import require_auth
from tasks import warm_vehicle_cache_task, generate_report_task

tasks_bp = Blueprint('tasks', __name__, url_prefix='/pos/api/tasks')


@tasks_bp.route('/warm-cache', methods=['POST'])
@require_auth()
def enqueue_warm_cache():
    """Enqueue vehicle cache warming task."""
    task = warm_vehicle_cache_task.apply_async()
    return jsonify({'task_id': task.id, 'status': 'queued'})


@tasks_bp.route('/report', methods=['POST'])
@require_auth()
def enqueue_report():
    """Enqueue report generation task."""
    data = request.get_json() or {}
    report_type = data.get('report_type', 'sales')
    params = data.get('params', {})
    tenant_id = getattr(request, 'tenant_id', None)
    task = generate_report_task.apply_async(args=[report_type, params, tenant_id])
    return jsonify({'task_id': task.id, 'status': 'queued'})


@tasks_bp.route('/<task_id>/status', methods=['GET'])
@require_auth()
def task_status(task_id):
    """Get status of a background task."""
    from celery_app import celery
    result = celery.AsyncResult(task_id)
    response = {
        'task_id': task_id,
        'status': result.status,
    }
    if result.status == 'PROGRESS':
        response['meta'] = result.info
    elif result.successful():
        response['result'] = result.result
    elif result.failed():
        response['error'] = str(result.result)
    return jsonify(response)
