<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

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

/**
 * @implements ProviderInterface<EvaluationResource>
 */
final readonly class EvaluationItemProvider implements ProviderInterface
{
    public function __construct(
        private EvaluationRepository $evaluationRepository,
        private TenantContext $tenantContext,
        private Security $security,
        private ClassRepository $classRepository,
        private SubjectRepository $subjectRepository,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): EvaluationResource
    {
        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 $id */
        $id = $uriVariables['id'];

        $evaluation = $this->evaluationRepository->findById(
            EvaluationId::fromString($id),
            $this->tenantContext->getCurrentTenantId(),
        );

        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.');
        }

        $class = $this->classRepository->findById($evaluation->classId);
        $subject = $this->subjectRepository->findById($evaluation->subjectId);

        return EvaluationResource::fromDomain(
            $evaluation,
            $class !== null ? (string) $class->name : null,
            $subject !== null ? (string) $subject->name : null,
        );
    }
}
