<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Exception\SubjectNotFoundException;
use App\Administration\Domain\Model\Subject\SubjectId;
use App\Administration\Domain\Repository\SubjectRepository;
use App\Administration\Infrastructure\Api\Resource\SubjectResource;
use App\Administration\Infrastructure\Security\SubjectVoter;
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 une matière par son ID.
 *
 * @implements ProviderInterface<SubjectResource>
 */
final readonly class SubjectItemProvider implements ProviderInterface
{
    public function __construct(
        private SubjectRepository $subjectRepository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

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

        /** @var string|null $subjectId */
        $subjectId = $uriVariables['id'] ?? null;
        if ($subjectId === null) {
            throw new NotFoundHttpException('Matière non trouvée.');
        }

        try {
            $subject = $this->subjectRepository->get(SubjectId::fromString($subjectId));
        } catch (SubjectNotFoundException|InvalidUuidStringException) {
            throw new NotFoundHttpException('Matière non trouvée.');
        }

        // Vérifier que la matière appartient au tenant actuel
        if ((string) $subject->tenantId !== (string) $this->tenantContext->getCurrentTenantId()) {
            throw new NotFoundHttpException('Matière non trouvée.');
        }

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

        return SubjectResource::fromDomain($subject);
    }
}
