<?php

declare(strict_types=1);

namespace App\Controller\Mail;

use App\Mail\Exception\MailProviderException;
use App\Mail\MailProviderInterface;
use App\Repository\MailMessageRepository;
use App\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 MailMessageRepository $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->find($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()]);
    }
}
