<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Repository\ProjectRepositoryInterface;
use App\Module\ProjectManagement\Domain\Repository\TaskRepositoryInterface;
use App\Shared\Infrastructure\Mcp\Serializer;
use InvalidArgumentException;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use function sprintf;

#[McpTool(name: 'get-project', description: 'Get project details with task count summary per status')]
class GetProjectTool
{
    public function __construct(
        private readonly ProjectRepositoryInterface $projectRepository,
        private readonly TaskRepositoryInterface $taskRepository,
        private readonly Security $security,
    ) {}

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

        $project = $this->projectRepository->findById($id);

        if (null === $project) {
            throw new InvalidArgumentException(sprintf('Project with ID %d not found.', $id));
        }

        // Count tasks per status
        $qb = $this->taskRepository->createQueryBuilder('t')
            ->select('s.label AS statusLabel, COUNT(t.id) AS taskCount')
            ->leftJoin('t.status', 's')
            ->where('t.project = :project')
            ->setParameter('project', $project)
            ->groupBy('s.id, s.label')
        ;

        $statusCounts = [];
        $totalTasks   = 0;
        foreach ($qb->getQuery()->getResult() as $row) {
            $label                = $row['statusLabel'] ?? 'No status';
            $count                = (int) $row['taskCount'];
            $statusCounts[$label] = $count;
            $totalTasks += $count;
        }

        return json_encode(Serializer::project($project) + [
            'taskSummary' => $statusCounts,
            'totalTasks'  => $totalTasks,
        ]);
    }
}
