<?php

namespace FacturaScripts\Plugins\Partes\Services\Task;

class TaskUpdateService
{
    public function __construct(
        private readonly TaskPersistenceService $persistence,
        private readonly TaskOperarioService $operarioService,
        private readonly TaskChecklistService $checklistService,
        private readonly TaskAttachmentService $attachmentService
    ) {
    }

    public function handle(TaskContext $context): ?int
    {
        if (!$context->shouldProcess()) {
            return null;
        }

        if (!$this->persistence->prepareTask($context)) {
            return null;
        }

        $this->persistence->applyTaskData($context);
        $this->operarioService->prepareAssignments($context);

        $taskId = $this->persistence->saveTask($context);
        if (null === $taskId) {
            return null;
        }

        $this->operarioService->persistAssignments($context, $taskId);

        $this->attachmentService->processUploads($context, $taskId);

        $subtaskTargets = $this->checklistService->sync($context, $taskId, $context->task());

        $this->attachmentService->processTokens($context, $taskId, $subtaskTargets);
        $this->attachmentService->processCleanup($context, $taskId);

        return $taskId;
    }
}
