<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\GetSubjects;

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

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

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

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