<?php

declare(strict_types=1);

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

use App\Module\Absence\Domain\Enum\AbsenceType;
use App\Module\Absence\Domain\Repository\AbsenceBalanceRepositoryInterface;
use App\Module\Core\Domain\Repository\UserRepositoryInterface;
use App\Shared\Infrastructure\Mcp\Serializer;
use InvalidArgumentException;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use function sprintf;

#[McpTool(name: 'list-absence-balances', description: 'List leave balances. Optional filters: userId, type (cp, mariage_pacs, conge_parental, deces, maladie), period (e.g. "2025-2026" or "2025").')]
class ListAbsenceBalancesTool
{
    public function __construct(
        private readonly AbsenceBalanceRepositoryInterface $balanceRepository,
        private readonly UserRepositoryInterface $userRepository,
        private readonly Security $security,
    ) {}

    public function __invoke(?int $userId = null, ?string $type = null, ?string $period = null): string
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedException('Access denied: ROLE_USER required.');
        }

        $criteria = [];
        if (null !== $userId) {
            $user = $this->userRepository->findById($userId);
            if (null === $user) {
                throw new InvalidArgumentException(sprintf('User with ID %d not found.', $userId));
            }
            $criteria['user'] = $user;
        }
        if (null !== $type) {
            $criteria['type'] = AbsenceType::tryFrom($type)
                ?? throw new InvalidArgumentException(sprintf('Unknown absence type "%s".', $type));
        }
        if (null !== $period) {
            $criteria['period'] = $period;
        }

        $balances = $this->balanceRepository->findBy($criteria, ['period' => 'DESC']);

        return json_encode(array_map(Serializer::absenceBalance(...), $balances));
    }
}
