<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\GetClasses;

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

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

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

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