<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Scolarite\Domain\Model\TeacherReplacement\TeacherReplacementId;
use App\Scolarite\Domain\Repository\TeacherReplacementRepository;
use App\Scolarite\Infrastructure\Api\Resource\TeacherReplacementResource;
use App\Scolarite\Infrastructure\Security\TeacherReplacementVoter;
use App\Shared\Domain\Tenant\TenantId;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
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;

/**
 * @implements ProviderInterface<TeacherReplacementResource>
 */
final readonly class TeacherReplacementItemProvider implements ProviderInterface
{
    public function __construct(
        private TeacherReplacementRepository $replacementRepository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): TeacherReplacementResource
    {
        if (!$this->authorizationChecker->isGranted(TeacherReplacementVoter::DELETE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à terminer les remplacements.');
        }

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

        /** @var string $id */
        $id = $uriVariables['id'];
        $tenantId = TenantId::fromString((string) $this->tenantContext->getCurrentTenantId());

        $replacement = $this->replacementRepository->findById(
            TeacherReplacementId::fromString($id),
            $tenantId,
        );

        if ($replacement === null) {
            throw new NotFoundHttpException('Remplacement non trouvé.');
        }

        return TeacherReplacementResource::fromDomain($replacement);
    }
}
