<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Comment;

use App\Entity\Comment;
use App\Mcp\Tool\McpToolHelper;
use App\Repository\ProfileRepository;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;
use Symfony\Bundle\SecurityBundle\Security;

#[McpTool(
    name: 'resolve_comment',
    description: 'Mark a comment as resolved. Sets status to "resolved" with resolver info. Requires ROLE_GESTIONNAIRE.',
)]
class ResolveCommentTool
{
    use McpToolHelper;

    public function __construct(
        private readonly EntityManagerInterface $em,
        private readonly Security $security,
        private readonly ProfileRepository $profiles,
    ) {}

    public function __invoke(string $commentId): CallToolResult
    {
        $this->requireRole($this->security, 'ROLE_GESTIONNAIRE');

        $comment = $this->em->getRepository(Comment::class)->find($commentId);
        if (!$comment) {
            $this->mcpError('NotFound', 'Commentaire introuvable.');
        }

        $user    = $this->security->getUser();
        $profile = $user ? $this->profiles->find($user->getUserIdentifier()) : null;

        $resolverName = 'Inconnu';
        $resolverId   = null;
        if ($profile) {
            $resolverId   = $profile->getId();
            $resolverName = trim(sprintf('%s %s', $profile->getFirstName(), $profile->getLastName()));
            if ('' === $resolverName) {
                $resolverName = $profile->getEmail() ?? 'Inconnu';
            }
        }

        $comment->setStatus('resolved');
        $comment->setResolvedById($resolverId);
        $comment->setResolvedByName($resolverName);
        $comment->setResolvedAt(new DateTimeImmutable());

        $this->em->flush();

        return $this->jsonResponse([
            'id'             => $comment->getId(),
            'status'         => $comment->getStatus(),
            'resolvedById'   => $comment->getResolvedById(),
            'resolvedByName' => $comment->getResolvedByName(),
        ]);
    }
}
