<?php

declare(strict_types=1);

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

use App\Module\Absence\Domain\Repository\AbsenceRequestRepositoryInterface;
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-absence-request', description: 'Permanently delete an absence request (admin). Does not adjust balances — use cancel-absence-request first if the days must be credited back.')]
class DeleteAbsenceRequestTool
{
    public function __construct(
        private readonly AbsenceRequestRepositoryInterface $requestRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

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

        $request = $this->requestRepository->findById($id);
        if (null === $request) {
            throw new InvalidArgumentException(sprintf('AbsenceRequest with ID %d not found.', $id));
        }

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

        return json_encode(['success' => true, 'message' => sprintf('AbsenceRequest %d deleted.', $id)]);
    }
}
