<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\GetUsers;

use App\Administration\Application\Dto\PaginatedResult;
use App\Administration\Application\Port\PaginatedUsersReader;
use App\Administration\Application\Service\Cache\PaginatedQueryCache;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler(bus: 'query.bus')]
final readonly class GetUsersHandler
{
    public function __construct(
        private PaginatedUsersReader $reader,
        private PaginatedQueryCache $cache,
    ) {
    }

    /**
     * @return PaginatedResult<UserDto>
     */
    public function __invoke(GetUsersQuery $query): PaginatedResult
    {
        /* @var PaginatedResult<UserDto> */
        return $this->cache->getOrLoad(
            'users',
            $query->tenantId,
            $this->cacheParams($query),
            fn (): PaginatedResult => $this->reader->findPaginated(
                tenantId: $query->tenantId,
                role: $query->role,
                statut: $query->statut,
                search: $query->search,
                page: $query->page,
                limit: $query->limit,
            ),
        );
    }

    /**
     * @return array<string, mixed>
     */
    private function cacheParams(GetUsersQuery $query): array
    {
        return [
            'page' => $query->page,
            'limit' => $query->limit,
            'role' => $query->role,
            'statut' => $query->statut,
            'search' => $query->search,
        ];
    }
}
