<?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}/flag', name: 'mail_message_flag', methods: ['POST'], priority: 1, requirements: ['id' => '\d+'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class MailMessageFlagController 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);
        $flagged = (bool) ($body['flagged'] ?? true);

        try {
            $this->mailProvider->markFlagged($message->getFolder()->getPath(), $message->getUid(), $flagged);
        } catch (MailProviderException) {
            // Non bloquant
        }

        $message->setIsFlagged($flagged);
        $this->em->flush();

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