<?php

declare(strict_types=1);

namespace App\Module\ProjectManagement\Infrastructure\Mcp\Tool\TaskMeta;

use App\Module\ProjectManagement\Domain\Entity\TaskStatus;
use App\Module\ProjectManagement\Domain\Enum\StatusCategory;
use App\Module\ProjectManagement\Domain\Repository\WorkflowRepositoryInterface;
use Doctrine\ORM\EntityManagerInterface;
use InvalidArgumentException;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use function sprintf;

#[McpTool(name: 'create-status', description: 'Create a task status inside a workflow (admin). Statuses are NOT global: each belongs to a workflow (use list-workflows for IDs). category = todo|in_progress|blocked|review|done.')]
class CreateStatusTool
{
    public function __construct(
        private readonly WorkflowRepositoryInterface $workflowRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(
        int $workflowId,
        string $label,
        string $category,
        ?string $color = null,
        ?int $position = null,
        ?bool $isFinal = null,
    ): string {
        if (!$this->security->isGranted('ROLE_ADMIN')) {
            throw new AccessDeniedException('Access denied: ROLE_ADMIN required.');
        }

        $workflow = $this->workflowRepository->findById($workflowId);
        if (null === $workflow) {
            throw new InvalidArgumentException(sprintf('Workflow with ID %d not found.', $workflowId));
        }

        $categoryEnum = StatusCategory::tryFrom($category)
            ?? throw new InvalidArgumentException(sprintf('Unknown status category "%s".', $category));

        $status = new TaskStatus();
        $status->setWorkflow($workflow);
        $status->setLabel($label);
        $status->setCategory($categoryEnum);
        if (null !== $color) {
            $status->setColor($color);
        }
        if (null !== $position) {
            $status->setPosition($position);
        }
        if (null !== $isFinal) {
            $status->setIsFinal($isFinal);
        }

        $this->entityManager->persist($status);
        $this->entityManager->flush();

        return json_encode([
            'id'         => $status->getId(),
            'label'      => $status->getLabel(),
            'color'      => $status->getColor(),
            'position'   => $status->getPosition(),
            'isFinal'    => $status->getIsFinal(),
            'category'   => $status->getCategory()->value,
            'workflowId' => $workflow->getId(),
        ]);
    }
}
