<?php

declare(strict_types=1);

namespace App\Module\Mail\Application\MessageHandler;

use App\Module\Mail\Application\Message\MailSyncRequested;
use App\Module\Mail\Application\Service\MailSyncService;
use App\Module\Mail\Domain\Repository\MailFolderRepositoryInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Throwable;

#[AsMessageHandler]
final readonly class MailSyncRequestedHandler
{
    public function __construct(
        private MailSyncService $mailSyncService,
        private MailFolderRepositoryInterface $folderRepository,
        private LoggerInterface $logger,
    ) {}

    public function __invoke(MailSyncRequested $message): void
    {
        try {
            if (null !== $message->folderPath) {
                $folder = $this->folderRepository->findByPath($message->folderPath);
                if (null !== $folder) {
                    $report = $this->mailSyncService->syncFolder($folder);
                    $this->logger->info(sprintf(
                        'MailSyncRequested handled for folder "%s": %d created, %d updated, %d deleted',
                        $message->folderPath,
                        $report->createdCount,
                        $report->updatedCount,
                        $report->deletedCount,
                    ));
                } else {
                    $this->logger->warning(sprintf('MailSyncRequested: folder "%s" not found in DB', $message->folderPath));
                }
            } else {
                $report = $this->mailSyncService->syncAll();
                $this->logger->info(sprintf(
                    'MailSyncRequested handled (all folders): %d created, %d updated, %d deleted, %d folders scanned',
                    $report->createdCount,
                    $report->updatedCount,
                    $report->deletedCount,
                    $report->foldersScanned,
                ));
            }
        } catch (Throwable $e) {
            $this->logger->error('MailSyncRequestedHandler failed: '.$e->getMessage());
        }
    }
}
