<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Repository\WorkflowRepositoryInterface;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

#[McpTool(
    name: 'list-workflows',
    description: 'List all workflows (status templates) with their statuses grouped under each workflow. Each project has one workflow that defines its kanban columns.',
)]
class ListWorkflowsTool
{
    public function __construct(
        private readonly WorkflowRepositoryInterface $workflowRepository,
        private readonly Security $security,
    ) {}

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

        $workflows = $this->workflowRepository->findBy([], ['position' => 'ASC']);

        return json_encode(array_map(fn ($w) => [
            'id'        => $w->getId(),
            'name'      => $w->getName(),
            'isDefault' => $w->isDefault(),
            'position'  => $w->getPosition(),
            'statuses'  => array_map(fn ($s) => [
                'id'       => $s->getId(),
                'label'    => $s->getLabel(),
                'color'    => $s->getColor(),
                'position' => $s->getPosition(),
                'isFinal'  => $s->getIsFinal(),
                'category' => $s->getCategory()->value,
            ], $w->getStatuses()->toArray()),
        ], $workflows));
    }
}
