from django.db import transaction

from intranet.femida.src.actionlog.models import actionlog
from intranet.femida.src.celery_app import app
from intranet.femida.src.hire_orders.models import HireOrder
from intranet.femida.src.utils.lock import locked_task


@app.autoretry_task(max_retries=5)
@locked_task(delay=0)
@transaction.atomic
def perform_hire_order_action_task(hire_order_id, action_name, **params):
    from intranet.femida.src.hire_orders.workflow import HireOrderWorkflow
    with actionlog.init(f'hire_order_{action_name}'):
        instance = (
            HireOrder.objects
            .select_for_update()
            .get(id=hire_order_id)
        )
        workflow = HireOrderWorkflow(instance, user=None)
        workflow.perform_action(action_name, **params)
