<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\GetAllAssignments;

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

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

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

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