<?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 Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Throwable;

#[Route('/api/mail/configuration/test', name: 'mail_configuration_test', methods: ['POST'], priority: 1)]
#[IsGranted('ROLE_ADMIN')]
class MailTestConnectionController extends AbstractController
{
    public function __construct(
        private readonly MailProviderInterface $mailProvider,
    ) {}

    public function __invoke(): JsonResponse
    {
        try {
            $foldersCount = $this->mailProvider->testConnection();

            return $this->json([
                'ok'           => true,
                'foldersCount' => $foldersCount,
            ]);
        } catch (MailProviderException $e) {
            return $this->json([
                'ok'     => false,
                'error'  => 'Connexion IMAP impossible. Vérifiez la configuration.',
                'detail' => $e->getMessage(),
            ]);
        } catch (Throwable $e) {
            return $this->json([
                'ok'     => false,
                'error'  => 'Erreur inattendue lors du test de connexion.',
                'detail' => $e->getMessage(),
            ]);
        }
    }
}
