<?php

declare(strict_types=1);

namespace App\Module\Mail\Infrastructure\Controller;

use App\Module\Mail\Domain\Repository\MailFolderRepositoryInterface;
use App\Module\Mail\Infrastructure\Security\MailAccessChecker;
use DateTimeInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/api/mail/folders', name: 'mail_folders_list', methods: ['GET'], priority: 1)]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class MailFoldersListController extends AbstractController
{
    public function __construct(
        private readonly MailFolderRepositoryInterface $folderRepository,
        private readonly MailAccessChecker $accessChecker,
    ) {}

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

        $folders = $this->folderRepository->findAllOrderedByPath();

        $data = array_map(static fn ($folder) => [
            'id'           => $folder->getId(),
            'path'         => $folder->getPath(),
            'displayName'  => $folder->getDisplayName(),
            'parentPath'   => $folder->getParentPath(),
            'unreadCount'  => $folder->getUnreadCount(),
            'totalCount'   => $folder->getTotalCount(),
            'lastSyncedAt' => $folder->getLastSyncedAt()?->format(DateTimeInterface::ATOM),
        ], $folders);

        return $this->json($data);
    }
}
