<?php

declare(strict_types=1);

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

use App\Module\Core\Infrastructure\Doctrine\DoctrineUserRepository;
use App\Module\ProjectManagement\Domain\Entity\Task;
use App\Module\ProjectManagement\Domain\Repository\ProjectRepositoryInterface;
use App\Module\ProjectManagement\Domain\Repository\TaskEffortRepositoryInterface;
use App\Module\ProjectManagement\Domain\Repository\TaskGroupRepositoryInterface;
use App\Module\ProjectManagement\Domain\Repository\TaskPriorityRepositoryInterface;
use App\Module\ProjectManagement\Domain\Repository\TaskRepositoryInterface;
use App\Module\ProjectManagement\Domain\Repository\TaskStatusRepositoryInterface;
use App\Module\ProjectManagement\Domain\Repository\TaskTagRepositoryInterface;
use App\Module\ProjectManagement\Infrastructure\Service\CalDavService;
use App\Shared\Infrastructure\Mcp\Serializer;
use DateTimeImmutable;
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-task', description: 'Create a new task in a project. The task number is auto-generated. Use list-statuses, list-priorities, list-efforts, list-tags, list-groups to discover valid IDs. The status parameter must reference a status that belongs to the target project\'s workflow — otherwise the call is rejected with a validation error.')]
class CreateTaskTool
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly ProjectRepositoryInterface $projectRepository,
        private readonly TaskRepositoryInterface $taskRepository,
        private readonly TaskStatusRepositoryInterface $taskStatusRepository,
        private readonly TaskPriorityRepositoryInterface $taskPriorityRepository,
        private readonly TaskEffortRepositoryInterface $taskEffortRepository,
        private readonly TaskGroupRepositoryInterface $taskGroupRepository,
        private readonly TaskTagRepositoryInterface $taskTagRepository,
        private readonly DoctrineUserRepository $userRepository,
        private readonly Security $security,
        private readonly CalDavService $calDavService,
    ) {}

    /**
     * @param int[] $tagIds          IDs of the tags to attach
     * @param int[] $collaboratorIds IDs of the collaborators to attach
     */
    public function __invoke(
        int $projectId,
        string $title,
        ?string $description = null,
        ?int $statusId = null,
        ?int $priorityId = null,
        ?int $effortId = null,
        ?int $assigneeId = null,
        ?int $groupId = null,
        ?array $tagIds = null,
        ?array $collaboratorIds = null,
        ?string $scheduledStart = null,
        ?string $scheduledEnd = null,
        ?string $deadline = null,
        ?bool $syncToCalendar = null,
    ): string {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedException('Access denied: ROLE_USER required.');
        }

        $project = $this->projectRepository->findById($projectId);
        if (null === $project) {
            throw new InvalidArgumentException(sprintf('Project with ID %d not found.', $projectId));
        }

        $task = new Task();
        $task->setProject($project);
        $task->setTitle($title);

        if (null !== $description) {
            $task->setDescription($description);
        }
        if (null !== $statusId) {
            $status = $this->taskStatusRepository->findById($statusId);
            if (null === $status) {
                throw new InvalidArgumentException(sprintf('TaskStatus with ID %d not found.', $statusId));
            }
            $task->setStatus($status);
        }
        if (null !== $priorityId) {
            $priority = $this->taskPriorityRepository->findById($priorityId);
            if (null === $priority) {
                throw new InvalidArgumentException(sprintf('TaskPriority with ID %d not found.', $priorityId));
            }
            $task->setPriority($priority);
        }
        if (null !== $effortId) {
            $effort = $this->taskEffortRepository->findById($effortId);
            if (null === $effort) {
                throw new InvalidArgumentException(sprintf('TaskEffort with ID %d not found.', $effortId));
            }
            $task->setEffort($effort);
        }
        if (null !== $assigneeId) {
            $assignee = $this->userRepository->find($assigneeId);
            if (null === $assignee) {
                throw new InvalidArgumentException(sprintf('User with ID %d not found.', $assigneeId));
            }
            $task->setAssignee($assignee);
        }
        if (null !== $groupId) {
            $group = $this->taskGroupRepository->findById($groupId);
            if (null === $group) {
                throw new InvalidArgumentException(sprintf('TaskGroup with ID %d not found.', $groupId));
            }
            $task->setGroup($group);
        }
        if (null !== $tagIds) {
            foreach ($tagIds as $tagId) {
                $tag = $this->taskTagRepository->findById($tagId);
                if (null === $tag) {
                    throw new InvalidArgumentException(sprintf('TaskTag with ID %d not found.', $tagId));
                }
                $task->addTag($tag);
            }
        }
        if (null !== $collaboratorIds) {
            foreach ($collaboratorIds as $collaboratorId) {
                $collaborator = $this->userRepository->find($collaboratorId);
                if (null === $collaborator) {
                    throw new InvalidArgumentException(sprintf('User with ID %d not found.', $collaboratorId));
                }
                if (null !== $assigneeId && $collaboratorId === $assigneeId) {
                    throw new InvalidArgumentException('A collaborator cannot be the assignee.');
                }
                $task->addCollaborator($collaborator);
            }
        }
        if (null !== $scheduledStart) {
            $task->setScheduledStart(new DateTimeImmutable($scheduledStart));
        }
        if (null !== $scheduledEnd) {
            $task->setScheduledEnd(new DateTimeImmutable($scheduledEnd));
        }
        if (null !== $deadline) {
            $task->setDeadline(new DateTimeImmutable($deadline));
        }
        if (null !== $syncToCalendar) {
            $task->setSyncToCalendar($syncToCalendar);
        }

        $this->entityManager->wrapInTransaction(function () use ($task, $project): void {
            $task->setNumber($this->taskRepository->findMaxNumberByProjectForUpdate($project) + 1);
            $this->entityManager->persist($task);
            $this->entityManager->flush();
        });

        $this->calDavService->syncTask($task);
        $this->entityManager->flush();

        return json_encode([
            'id'             => $task->getId(),
            'number'         => $task->getNumber(),
            'title'          => $task->getTitle(),
            'description'    => $task->getDescription(),
            'status'         => Serializer::status($task->getStatus()),
            'priority'       => Serializer::priority($task->getPriority()),
            'effort'         => Serializer::effort($task->getEffort()),
            'assignee'       => Serializer::user($task->getAssignee()),
            'collaborators'  => Serializer::users($task->getCollaborators()),
            'group'          => Serializer::groupRef($task->getGroup()),
            'project'        => Serializer::projectRef($project),
            'tags'           => Serializer::tags($task->getTags()),
            'archived'       => $task->isArchived(),
            'scheduledStart' => $task->getScheduledStart()?->format('c'),
            'scheduledEnd'   => $task->getScheduledEnd()?->format('c'),
            'deadline'       => $task->getDeadline()?->format('c'),
            'syncToCalendar' => $task->isSyncToCalendar(),
        ]);
    }
}
