from celery import Task

from core.celery_app import celery_app
from core.database import CoreSessionLocal
from core.exceptions import ValidationException

from api.v1.modules.a76.invoices.models import InvoiceHeader
from .main_process import main_process


def _progress(task: Task, current: int, status: str) -> None:
    task.update_state(state="PROGRESS", meta={"current": current, "status": status})


@celery_app.task(bind=True, name="process_export_invoice_task")
def process_export_invoice_task(self: Task, invoice_id: int, tenant_id: str, company_id: str) -> dict:
    """
    Procesa una factura de exportación ejecutando todas las validaciones y
    actualizaciones del proceso principal de exportación con reporte de progreso.
    """
    db = CoreSessionLocal()
    try:
        _progress(self, 5, "Cargando factura...")
        invoice: InvoiceHeader | None = db.get(InvoiceHeader, invoice_id)
        if invoice is None:
            return {
                "status": "error",
                "message": f"Factura con id {invoice_id} no encontrada.",
                "errors": [],
            }

        _progress(self, 10, "Procesando factura de exportación...")
        result = main_process(db, invoice, tenant_id, company_id)

        db.commit()
        _progress(self, 100, "Proceso completado.")
        return {**result, "invoice_id": invoice_id}

    except ValidationException as exc:
        db.rollback()
        return {
            "status": "validation_error",
            "message": exc.message,
            "errors": exc.errors,
        }
    except Exception as exc:
        db.rollback()
        raise exc
    finally:
        db.close()
