<?php

declare(strict_types=1);

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

use App\Module\Absence\Domain\Repository\AbsencePolicyRepositoryInterface;
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-policy', description: 'Update an absence policy (admin). Only provided fields change.')]
class UpdateAbsencePolicyTool
{
    public function __construct(
        private readonly AbsencePolicyRepositoryInterface $policyRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(
        int $id,
        ?float $daysPerYear = null,
        ?float $daysPerEvent = null,
        ?bool $justificationRequired = null,
        ?int $noticeDays = null,
        ?bool $countWorkingDaysOnly = null,
        ?bool $active = null,
    ): string {
        if (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Access denied: ROLE_ADMIN required.');
        }

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

        if (null !== $daysPerYear) {
            $policy->setDaysPerYear($daysPerYear);
        }
        if (null !== $daysPerEvent) {
            $policy->setDaysPerEvent($daysPerEvent);
        }
        if (null !== $justificationRequired) {
            $policy->setJustificationRequired($justificationRequired);
        }
        if (null !== $noticeDays) {
            $policy->setNoticeDays($noticeDays);
        }
        if (null !== $countWorkingDaysOnly) {
            $policy->setCountWorkingDaysOnly($countWorkingDaysOnly);
        }
        if (null !== $active) {
            $policy->setActive($active);
        }

        $this->entityManager->flush();

        return json_encode(Serializer::absencePolicy($policy));
    }
}
