<?php

declare(strict_types=1);

namespace App\Controller\Mail;

use App\Entity\Task;
use App\Repository\TaskMailLinkRepository;
use App\Security\MailAccessChecker;
use DateTimeInterface;
use Doctrine\ORM\EntityManagerInterface;
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 EntityManagerInterface $em,
        private readonly TaskMailLinkRepository $linkRepository,
        private readonly MailAccessChecker $accessChecker,
    ) {}

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

        $task = $this->em->getRepository(Task::class)->find($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);
    }
}
