<?php

declare(strict_types=1);

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

use App\Module\Directory\Domain\Repository\AddressRepositoryInterface;
use App\Module\Directory\Domain\Repository\CommercialReportRepositoryInterface;
use App\Module\Directory\Domain\Repository\ContactRepositoryInterface;
use App\Module\Directory\Domain\Repository\PrestataireRepositoryInterface;
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: 'get-prestataire', description: 'Get a prestataire by ID, with its linked contacts, addresses, and commercial reports.')]
class GetPrestataireTool
{
    public function __construct(
        private readonly PrestataireRepositoryInterface $prestataireRepository,
        private readonly ContactRepositoryInterface $contactRepository,
        private readonly AddressRepositoryInterface $addressRepository,
        private readonly CommercialReportRepositoryInterface $reportRepository,
        private readonly Security $security,
    ) {}

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

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

        $payload             = Serializer::prestataire($prestataire);
        $payload['contacts'] = array_map(
            fn ($c) => Serializer::contact($c),
            $this->contactRepository->findBy(['prestataire' => $prestataire], ['lastName' => 'ASC'])
        );
        $payload['addresses'] = array_map(
            fn ($a) => Serializer::address($a),
            $this->addressRepository->findBy(['prestataire' => $prestataire], ['id' => 'ASC'])
        );
        $payload['reports'] = array_map(
            fn ($r) => Serializer::commercialReport($r),
            $this->reportRepository->findBy(['prestataire' => $prestataire], ['occurredAt' => 'DESC'])
        );

        return json_encode($payload);
    }
}
