<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Domain\Model\Evaluation\EvaluationId;
use App\Scolarite\Domain\Repository\EvaluationRepository;
use App\Scolarite\Domain\Repository\EvaluationStatisticsRepository;
use App\Scolarite\Infrastructure\Api\Resource\EvaluationStatisticsResource;
use App\Shared\Infrastructure\Tenant\TenantContext;
use InvalidArgumentException;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProviderInterface<EvaluationStatisticsResource>
 */
final readonly class EvaluationStatisticsProvider implements ProviderInterface
{
    public function __construct(
        private EvaluationRepository $evaluationRepository,
        private EvaluationStatisticsRepository $evaluationStatisticsRepository,
        private TenantContext $tenantContext,
        private Security $security,
    ) {
    }

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

        $user = $this->security->getUser();

        if (!$user instanceof SecurityUser) {
            throw new UnauthorizedHttpException('Bearer', 'Authentification requise.');
        }

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

        try {
            $evalId = EvaluationId::fromString($evaluationId);
        } catch (InvalidArgumentException) {
            throw new BadRequestHttpException('Identifiant d\'évaluation invalide.');
        }

        $tenantId = $this->tenantContext->getCurrentTenantId();

        $evaluation = $this->evaluationRepository->findById($evalId, $tenantId);

        if ($evaluation === null) {
            throw new NotFoundHttpException('Évaluation non trouvée.');
        }

        if ((string) $evaluation->teacherId !== $user->userId()) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas le propriétaire de cette évaluation.');
        }

        $statistics = $this->evaluationStatisticsRepository->findByEvaluation($evalId);

        if ($statistics === null) {
            throw new NotFoundHttpException('Statistiques non disponibles pour cette évaluation.');
        }

        return EvaluationStatisticsResource::fromStatistics($evaluationId, $statistics);
    }
}
