<?php

declare(strict_types=1);

namespace App\Module\Mail\Infrastructure\Controller;

use App\Module\Mail\Application\Message\MailSyncRequested;
use App\Module\Mail\Infrastructure\Security\MailAccessChecker;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/api/mail/sync', name: 'mail_sync_trigger', methods: ['POST'], priority: 1)]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class MailSyncTriggerController extends AbstractController
{
    public function __construct(
        private readonly MessageBusInterface $bus,
        private readonly MailAccessChecker $accessChecker,
    ) {}

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

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

        $this->bus->dispatch(new MailSyncRequested($folderPath));

        return $this->json(
            ['message' => 'Synchronisation démarrée en arrière-plan'],
            Response::HTTP_ACCEPTED
        );
    }
}
