<?php

declare(strict_types=1);

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

use App\Module\Absence\Domain\Repository\AbsenceBalanceRepositoryInterface;
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: 'update-absence-balance', description: 'Manually adjust a leave balance (admin regularisation). Only provided buckets change: acquired (N-1), acquiring (N), taken.')]
class UpdateAbsenceBalanceTool
{
    public function __construct(
        private readonly AbsenceBalanceRepositoryInterface $balanceRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(
        int $id,
        ?float $acquired = null,
        ?float $acquiring = null,
        ?float $taken = null,
    ): string {
        if (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Access denied: ROLE_ADMIN required.');
        }

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

        if (null !== $acquired) {
            $balance->setAcquired($acquired);
        }
        if (null !== $acquiring) {
            $balance->setAcquiring($acquiring);
        }
        if (null !== $taken) {
            $balance->setTaken($taken);
        }

        $this->entityManager->flush();

        return json_encode(Serializer::absenceBalance($balance));
    }
}
