<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Scolarite\Domain\Exception\ScheduleSlotNotFoundException;
use App\Scolarite\Domain\Model\Schedule\ScheduleSlotId;
use App\Scolarite\Domain\Repository\ScheduleSlotRepository;
use App\Scolarite\Infrastructure\Api\Resource\ScheduleSlotResource;
use App\Scolarite\Infrastructure\Security\ScheduleSlotVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * State Provider pour récupérer un créneau d'emploi du temps par son ID.
 *
 * @implements ProviderInterface<ScheduleSlotResource>
 */
final readonly class ScheduleSlotItemProvider implements ProviderInterface
{
    public function __construct(
        private ScheduleSlotRepository $repository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ScheduleSlotResource
    {
        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        if (!$this->authorizationChecker->isGranted(ScheduleSlotVoter::VIEW)) {
            throw new AccessDeniedHttpException("Vous n'êtes pas autorisé à consulter l'emploi du temps.");
        }

        /** @var string|null $slotId */
        $slotId = $uriVariables['id'] ?? null;
        if ($slotId === null) {
            throw new NotFoundHttpException('Créneau non trouvé.');
        }

        $tenantId = $this->tenantContext->getCurrentTenantId();

        try {
            $slot = $this->repository->get(ScheduleSlotId::fromString($slotId), $tenantId);
        } catch (ScheduleSlotNotFoundException|InvalidUuidStringException) {
            throw new NotFoundHttpException('Créneau non trouvé.');
        }

        return ScheduleSlotResource::fromDomain($slot);
    }
}
