<?php

namespace FacturaScripts\Plugins\Partes\Services\Task;

use FacturaScripts\Core\Base\DataBase\DataBaseWhere;
use FacturaScripts\Dinamic\Model\AttachedFile;
use FacturaScripts\Plugins\Partes\Model\Partes;

class TaskAttachmentService
{
    public function __construct(private readonly Partes $partes)
    {
    }

    public function processUploads(TaskContext $context, int $idTarea): void
    {
        $files = $context->files();

        if (isset($files['files']) && is_array($files['files']['tmp_name'] ?? null)) {
            $this->partes->guardarImagenTarea($files['files'], $idTarea);
        }

        if (isset($files['filesSubtarea'], $context->allPost()['idtareaSubtarea'])
            && is_array($files['filesSubtarea']['tmp_name'] ?? null)
        ) {
            $this->partes->guardarImagenTarea($files['filesSubtarea'], $context->allPost()['idtareaSubtarea']);
        }
    }

    public function processTokens(TaskContext $context, int $idTarea, array $subtaskTargets): void
    {
        $post = $context->allPost();

        $tokensTarea = Partes::normalizeAttachmentTokenList($post['filesTokens'] ?? null);
        if (!empty($tokensTarea)) {
            Partes::attachFilesByIdentifiers($tokensTarea, $idTarea);
        }

        $tokensPorSubtarea = Partes::normalizeAttachmentTokenMap($post['filesSubtareaTokens'] ?? null);
        if (!empty($tokensPorSubtarea)) {
            foreach ($tokensPorSubtarea as $rawId => $tokens) {
                $destino = Partes::resolveAttachmentTargetId($subtaskTargets, $rawId);
                if (null === $destino) {
                    continue;
                }
                Partes::attachFilesByIdentifiers($tokens, $destino);
            }
        }
    }

    public function processCleanup(TaskContext $context, int $idTarea): void
    {
        $post = $context->allPost();

        if (isset($post['comentarios'])) {
            $this->partes->saveComentarios($post['comentarios'], $idTarea);
        }

        if (!empty($post['imagenesBorradas'])) {
            $identifiers = array_filter(array_map('trim', explode(',', (string) $post['imagenesBorradas'])));
            if (!empty($identifiers)) {
                Partes::deleteAttachmentsByIdentifiers($identifiers);
            }
        }

        if (isset($post['baseidtareaimagen'])) {
            $tempId = Partes::normalizeAttachmentId($post['baseidtareaimagen']);
            $archivos = new AttachedFile();
            $where = [new DataBaseWhere('idtarea', $tempId)];
            foreach ($archivos->all($where) as $archivo) {
                $archivo->idtarea = $idTarea;
                $archivo->save();
            }
        }
    }
}
