<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Comment;

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

#[McpTool(
    name: 'create_comment',
    description: 'Create a comment on an entity (machine, piece, composant, product…). Requires ROLE_VIEWER.',
)]
class CreateCommentTool
{
    use McpToolHelper;

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

    public function __invoke(
        string $content,
        string $entityType,
        string $entityId,
        string $entityName = '',
    ): CallToolResult {
        $this->requireRole($this->security, 'ROLE_VIEWER');

        $content = trim($content);
        if ('' === $content) {
            $this->mcpError('Validation', 'Le contenu est requis.');
        }

        $allowedTypes = ['machine', 'piece', 'composant', 'product', 'piece_category', 'component_category', 'product_category', 'machine_skeleton'];
        if (!in_array($entityType, $allowedTypes, true)) {
            $this->mcpError('Validation', "Type d'entité invalide : {$entityType}.");
        }

        $entityId = trim($entityId);
        if ('' === $entityId) {
            $this->mcpError('Validation', "L'identifiant de l'entité est requis.");
        }

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

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

        $comment = new Comment();
        $comment->setContent($content);
        $comment->setEntityType($entityType);
        $comment->setEntityId($entityId);
        $comment->setEntityName('' !== $entityName ? $entityName : null);
        $comment->setAuthorId($authorId);
        $comment->setAuthorName($authorName);

        $this->em->persist($comment);
        $this->em->flush();

        return $this->jsonResponse([
            'id'         => $comment->getId(),
            'content'    => $comment->getContent(),
            'entityType' => $comment->getEntityType(),
            'entityId'   => $comment->getEntityId(),
            'entityName' => $comment->getEntityName(),
            'authorName' => $comment->getAuthorName(),
            'status'     => $comment->getStatus(),
        ]);
    }
}
