<?php

declare(strict_types=1);

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

use App\Module\Directory\Domain\Enum\ReportType;
use App\Module\Directory\Domain\Repository\CommercialReportRepositoryInterface;
use App\Shared\Infrastructure\Mcp\Serializer;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
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-commercial-report',
    description: 'Update a commercial report (admin). Only provided fields change. Parent (client/prospect/prestataire) is immutable.'
)]
class UpdateCommercialReportTool
{
    public function __construct(
        private readonly CommercialReportRepositoryInterface $reportRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

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

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

        if (null !== $subject) {
            $report->setSubject($subject);
        }
        if (null !== $body) {
            $report->setBody($body);
        }
        if (null !== $occurredAt) {
            try {
                $report->setOccurredAt(new DateTimeImmutable($occurredAt));
            } catch (Exception $e) {
                throw new InvalidArgumentException(sprintf('Invalid occurredAt "%s": %s', $occurredAt, $e->getMessage()));
            }
        }
        if (null !== $type) {
            $typeEnum = ReportType::tryFrom($type);
            if (null === $typeEnum) {
                throw new InvalidArgumentException(sprintf('Invalid type "%s". Allowed: note, call, meeting, email.', $type));
            }
            $report->setType($typeEnum);
        }

        $this->entityManager->flush();

        return json_encode(Serializer::commercialReport($report));
    }
}
