<?php

declare(strict_types=1);

namespace App\Module\ProjectManagement\Infrastructure\Mcp\Tool\Task;

use App\Module\ProjectManagement\Domain\Entity\TaskDocument;
use Doctrine\ORM\EntityManagerInterface;
use InvalidArgumentException;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use function sprintf;

#[McpTool(name: 'delete-task-document', description: 'Delete a document attached to a task, permanently. The underlying file is also removed from disk.')]
class DeleteTaskDocumentTool
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    /**
     * @param int $id ID of the task document to delete
     */
    public function __invoke(int $id): string
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedException('Access denied: ROLE_USER required.');
        }

        $document = $this->entityManager->find(TaskDocument::class, $id);
        if (null === $document) {
            throw new InvalidArgumentException(sprintf('Task document with ID %d not found.', $id));
        }

        $taskId       = $document->getTask()?->getId();
        $originalName = $document->getOriginalName();

        $this->entityManager->remove($document);
        $this->entityManager->flush();

        return json_encode([
            'success'      => true,
            'message'      => sprintf('Document "%s" (ID %d) deleted.', $originalName, $id),
            'id'           => $id,
            'taskId'       => $taskId,
            'originalName' => $originalName,
        ]);
    }
}
