<?php

declare(strict_types=1);

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

use App\Module\Absence\Application\Service\AbsenceBalanceService;
use App\Module\Absence\Domain\Enum\AbsenceStatus;
use App\Module\Absence\Domain\Repository\AbsenceRequestRepositoryInterface;
use App\Shared\Infrastructure\Mcp\Serializer;
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: 'cancel-absence-request', description: 'Cancel an absence request. A PENDING request releases its reserved days; an APPROVED request can only be cancelled by an admin and credits the taken days back. Already cancelled/rejected requests cannot be cancelled.')]
class CancelAbsenceRequestTool
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly AbsenceRequestRepositoryInterface $requestRepository,
        private readonly AbsenceBalanceService $balanceService,
        private readonly Security $security,
    ) {}

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

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

        $isAdmin = $this->security->isGranted('ROLE_ADMIN');
        $status  = $request->getStatus();

        if (AbsenceStatus::Pending === $status) {
            $this->balanceService->release($request, false);
        } elseif (AbsenceStatus::Approved === $status) {
            if (!$isAdmin) {
                throw new AccessDeniedException('Only an admin can cancel an approved request.');
            }
            $this->balanceService->release($request, true);
        } else {
            throw new InvalidArgumentException('This request can no longer be cancelled.');
        }

        $request->setStatus(AbsenceStatus::Cancelled);
        $this->entityManager->flush();

        return json_encode(Serializer::absenceRequest($request));
    }
}
