<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\UserRepository;
use App\Administration\Infrastructure\Api\Resource\ImageRightsResource;
use App\Administration\Infrastructure\Security\ImageRightsVoter;
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;

/**
 * @implements ProviderInterface<ImageRightsResource>
 */
final readonly class ImageRightsItemProvider implements ProviderInterface
{
    public function __construct(
        private UserRepository $userRepository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

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

        if (!$this->authorizationChecker->isGranted(ImageRightsVoter::EDIT)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à modifier les droits à l\'image.');
        }

        /** @var string|null $studentId */
        $studentId = $uriVariables['id'] ?? null;
        if ($studentId === null) {
            throw new NotFoundHttpException('Élève non trouvé.');
        }

        try {
            $user = $this->userRepository->get(UserId::fromString($studentId));
        } catch (UserNotFoundException|InvalidUuidStringException) {
            throw new NotFoundHttpException('Élève non trouvé.');
        }

        if ((string) $user->tenantId !== (string) $this->tenantContext->getCurrentTenantId()) {
            throw new NotFoundHttpException('Élève non trouvé.');
        }

        $resource = new ImageRightsResource();
        $resource->id = (string) $user->id;
        $resource->firstName = $user->firstName;
        $resource->lastName = $user->lastName;
        $resource->email = (string) $user->email;
        $resource->imageRightsStatus = $user->imageRightsStatus->value;
        $resource->imageRightsStatusLabel = $user->imageRightsStatus->label();
        $resource->imageRightsUpdatedAt = $user->imageRightsUpdatedAt;

        return $resource;
    }
}
