<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Scolarite\Application\Query\GetScheduleSlots\GetScheduleSlotsHandler;
use App\Scolarite\Application\Query\GetScheduleSlots\GetScheduleSlotsQuery;
use App\Scolarite\Infrastructure\Api\Resource\ScheduleSlotResource;
use App\Scolarite\Infrastructure\Security\ScheduleSlotVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * State Provider pour récupérer l'emploi du temps avec filtrage par classe ou enseignant.
 *
 * @implements ProviderInterface<ScheduleSlotResource>
 */
final readonly class ScheduleSlotCollectionProvider implements ProviderInterface
{
    public function __construct(
        private GetScheduleSlotsHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    /** @return array<ScheduleSlotResource> */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        if (!$this->authorizationChecker->isGranted(ScheduleSlotVoter::VIEW)) {
            throw new AccessDeniedHttpException("Vous n'êtes pas autorisé à consulter l'emploi du temps.");
        }

        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();
        /** @var array<string, string> $filters */
        $filters = $context['filters'] ?? [];

        $query = new GetScheduleSlotsQuery(
            tenantId: $tenantId,
            classId: isset($filters['classId']) ? (string) $filters['classId'] : null,
            teacherId: isset($filters['teacherId']) ? (string) $filters['teacherId'] : null,
        );

        $dtos = ($this->handler)($query);

        return array_map(ScheduleSlotResource::fromDto(...), $dtos);
    }
}
