<?php

declare(strict_types=1);

namespace App\Module\TimeTracking\Infrastructure\Mcp\Tool;

use App\Module\TimeTracking\Domain\Repository\TimeEntryRepositoryInterface;
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-time-entry', description: 'Delete a time entry permanently')]
class DeleteTimeEntryTool
{
    public function __construct(
        private readonly TimeEntryRepositoryInterface $timeEntryRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(int $id): string
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedException('Access denied: ROLE_USER required.');
        }

        $entry = $this->timeEntryRepository->findById($id);

        if (null === $entry) {
            throw new InvalidArgumentException(sprintf('TimeEntry with ID %d not found.', $id));
        }

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

        return json_encode([
            'success' => true,
            'message' => 'Time entry deleted.',
        ]);
    }
}
