<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Entity\Project;
use App\Module\ProjectManagement\Domain\Repository\TaskStatusRepositoryInterface;
use Doctrine\ORM\EntityManagerInterface;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

#[McpTool(
    name: 'list-statuses',
    description: 'List task statuses. With projectId, returns only the statuses of that project\'s workflow. Without projectId, returns ALL statuses across workflows (use list-workflows to see how they group).',
)]
class ListStatusesTool
{
    public function __construct(
        private readonly TaskStatusRepositoryInterface $taskStatusRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(?int $projectId = null): string
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedException('Access denied: ROLE_USER required.');
        }

        if (null !== $projectId) {
            $project = $this->entityManager->find(Project::class, $projectId);
            if (!$project) {
                return json_encode(['error' => 'Project not found.']);
            }
            $statuses = $project->getWorkflow()->getStatuses()->toArray();
        } else {
            $statuses = $this->taskStatusRepository->findBy([], ['position' => 'ASC']);
        }

        return json_encode(array_map(fn ($s) => [
            'id'         => $s->getId(),
            'label'      => $s->getLabel(),
            'color'      => $s->getColor(),
            'position'   => $s->getPosition(),
            'isFinal'    => $s->getIsFinal(),
            'category'   => $s->getCategory()->value,
            'workflowId' => $s->getWorkflow()?->getId(),
        ], $statuses));
    }
}
