<?php

declare(strict_types=1);

namespace App\Module\Mail\Infrastructure\Controller;

use App\Module\Mail\Domain\Repository\TaskMailLinkRepositoryInterface;
use App\Module\Mail\Infrastructure\Security\MailAccessChecker;
use App\Module\ProjectManagement\Domain\Repository\TaskRepositoryInterface;
use DateTimeInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/api/tasks/{id}/mails', name: 'task_mails_list', methods: ['GET'], priority: 1, requirements: ['id' => '\d+'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class TaskMailsListController extends AbstractController
{
    public function __construct(
        private readonly TaskRepositoryInterface $taskRepository,
        private readonly TaskMailLinkRepositoryInterface $linkRepository,
        private readonly MailAccessChecker $accessChecker,
    ) {}

    public function __invoke(int $id): JsonResponse
    {
        $this->accessChecker->ensureCanAccessMail($this->getUser());

        $task = $this->taskRepository->findById($id);
        if (null === $task) {
            throw new NotFoundHttpException('Task not found');
        }

        $links = $this->linkRepository->findByTask($task);

        $data = array_map(static fn ($link) => [
            'id'          => $link->getMailMessage()->getId(),
            'messageId'   => $link->getMailMessage()->getMessageId(),
            'subject'     => $link->getMailMessage()->getSubject(),
            'fromAddress' => $link->getMailMessage()->getFromAddress(),
            'fromName'    => $link->getMailMessage()->getFromName(),
            'sentAt'      => $link->getMailMessage()->getSentAt()->format(DateTimeInterface::ATOM),
            'isRead'      => $link->getMailMessage()->isRead(),
            'isFlagged'   => $link->getMailMessage()->isFlagged(),
            'snippet'     => $link->getMailMessage()->getSnippet(),
            'linkedAt'    => $link->getLinkedAt()->format(DateTimeInterface::ATOM),
        ], $links);

        return $this->json($data);
    }
}
