<?php

declare(strict_types=1);

namespace App\Module\Mail\Infrastructure\Controller;

use App\Module\Mail\Domain\Exception\MailProviderException;
use App\Module\Mail\Domain\Provider\MailProviderInterface;
use App\Module\Mail\Domain\Repository\MailMessageRepositoryInterface;
use App\Module\Mail\Infrastructure\Security\MailAccessChecker;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/api/mail/messages/{id}/read', name: 'mail_message_read', methods: ['POST'], priority: 1, requirements: ['id' => '\d+'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class MailMessageReadController extends AbstractController
{
    public function __construct(
        private readonly MailMessageRepositoryInterface $messageRepository,
        private readonly MailProviderInterface $mailProvider,
        private readonly EntityManagerInterface $em,
        private readonly MailAccessChecker $accessChecker,
    ) {}

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

        $message = $this->messageRepository->findById($id);
        if (null === $message) {
            throw new NotFoundHttpException('Message not found');
        }

        $body = json_decode($request->getContent(), true);
        $read = (bool) ($body['read'] ?? true);

        try {
            $this->mailProvider->markRead($message->getFolder()->getPath(), $message->getUid(), $read);
        } catch (MailProviderException) {
            // Non bloquant : on met quand meme a jour la BDD (sync IMAP au prochain cycle)
        }

        $message->setIsRead($read);
        $this->em->flush();

        return $this->json(['id' => $message->getId(), 'isRead' => $message->isRead()]);
    }
}
