<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\GetStudentsImageRights;

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

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

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

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