<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Model\TeacherAssignment\TeacherAssignmentId;
use App\Administration\Domain\Repository\TeacherAssignmentRepository;
use App\Administration\Infrastructure\Api\Resource\TeacherAssignmentResource;
use App\Administration\Infrastructure\Security\TeacherAssignmentVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use InvalidArgumentException;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProviderInterface<TeacherAssignmentResource>
 */
final readonly class TeacherAssignmentItemProvider implements ProviderInterface
{
    public function __construct(
        private TeacherAssignmentRepository $repository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

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

        if (!$this->authorizationChecker->isGranted(TeacherAssignmentVoter::DELETE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à supprimer cette affectation.');
        }

        /** @var string $id */
        $id = $uriVariables['id'] ?? '';

        try {
            $assignment = $this->repository->findById(
                TeacherAssignmentId::fromString($id),
                $this->tenantContext->getCurrentTenantId(),
            );
        } catch (InvalidArgumentException) {
            return null;
        }

        if ($assignment === null) {
            return null;
        }

        return TeacherAssignmentResource::fromDomain($assignment);
    }
}
