<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Model\SchoolClass\ClassId;
use App\Administration\Domain\Repository\ClassRepository;
use App\Administration\Infrastructure\Api\Resource\ClassResource;
use App\Administration\Infrastructure\Security\ClassVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use InvalidArgumentException;

use function is_string;

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;

/**
 * State Provider pour récupérer une classe par son ID.
 *
 * @implements ProviderInterface<ClassResource>
 */
final readonly class ClassItemProvider implements ProviderInterface
{
    public function __construct(
        private ClassRepository $classRepository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?ClassResource
    {
        $id = $uriVariables['id'] ?? null;

        if (!is_string($id)) {
            return null;
        }

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

        try {
            $classId = ClassId::fromString($id);
        } catch (InvalidArgumentException) {
            throw new NotFoundHttpException('Classe introuvable.');
        }

        $class = $this->classRepository->findById($classId);

        if ($class === null) {
            throw new NotFoundHttpException('Classe introuvable.');
        }

        // Vérifier que la classe appartient au tenant courant (comparaison par valeur string)
        if ((string) $class->tenantId !== (string) $this->tenantContext->getCurrentTenantId()) {
            throw new NotFoundHttpException('Classe introuvable.');
        }

        // Vérifier les permissions de lecture
        if (!$this->authorizationChecker->isGranted(ClassVoter::VIEW, $class)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir cette classe.');
        }

        $resource = new ClassResource();
        $resource->id = (string) $class->id;
        $resource->name = (string) $class->name;
        $resource->level = $class->level?->value;
        $resource->capacity = $class->capacity;
        $resource->description = $class->description;
        $resource->status = $class->status->value;
        $resource->createdAt = $class->createdAt;
        $resource->updatedAt = $class->updatedAt;

        return $resource;
    }
}
