<?php

declare(strict_types=1);

namespace App\Administration\Application\Query\GetParentInvitations;

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

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

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

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