<?php

declare(strict_types=1);

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

use App\Module\Core\Domain\Enum\ContractType;
use App\Module\Core\Infrastructure\Doctrine\DoctrineUserRepository;
use App\Shared\Infrastructure\Mcp\Serializer;
use DateTimeImmutable;
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-user', description: 'Update a user HR/profile fields (admin). Does NOT change password or roles. contractType = CDI|CDD|STAGE|ALTERNANCE|AUTRE. hireDate/endDate as YYYY-MM-DD. referencePeriodStart as MM-DD (e.g. 06-01).')]
class UpdateUserTool
{
    public function __construct(
        private readonly DoctrineUserRepository $userRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(
        int $id,
        ?bool $isEmployee = null,
        ?string $hireDate = null,
        ?string $endDate = null,
        ?string $contractType = null,
        ?float $workTimeRatio = null,
        ?float $annualLeaveDays = null,
        ?string $referencePeriodStart = null,
        ?float $initialLeaveBalance = null,
    ): string {
        if (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Access denied: ROLE_ADMIN required.');
        }

        $user = $this->userRepository->find($id);
        if (null === $user) {
            throw new InvalidArgumentException(sprintf('User with ID %d not found.', $id));
        }

        if (null !== $isEmployee) {
            $user->setIsEmployee($isEmployee);
        }
        if (null !== $hireDate) {
            $user->setHireDate(new DateTimeImmutable($hireDate));
        }
        if (null !== $endDate) {
            $user->setEndDate(new DateTimeImmutable($endDate));
        }
        if (null !== $contractType) {
            $user->setContractType(
                ContractType::tryFrom($contractType)
                    ?? throw new InvalidArgumentException(sprintf('Unknown contract type "%s".', $contractType)),
            );
        }
        if (null !== $workTimeRatio) {
            $user->setWorkTimeRatio($workTimeRatio);
        }
        if (null !== $annualLeaveDays) {
            $user->setAnnualLeaveDays($annualLeaveDays);
        }
        if (null !== $referencePeriodStart) {
            $user->setReferencePeriodStart($referencePeriodStart);
        }
        if (null !== $initialLeaveBalance) {
            $user->setInitialLeaveBalance($initialLeaveBalance);
        }

        $this->entityManager->flush();

        return json_encode(Serializer::userFull($user));
    }
}
