<?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\AcademicYearId;
use App\Administration\Domain\Model\User\Role;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\ClassAssignmentRepository;
use App\Administration\Domain\Repository\ClassRepository;
use App\Administration\Domain\Repository\UserRepository;
use App\Administration\Infrastructure\Api\Resource\StudentResource;
use App\Administration\Infrastructure\Security\StudentVoter;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Shared\Domain\Tenant\TenantId;
use App\Shared\Infrastructure\Tenant\TenantContext;
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;

/**
 * @implements ProviderInterface<StudentResource>
 */
final readonly class StudentItemProvider implements ProviderInterface
{
    public function __construct(
        private UserRepository $userRepository,
        private ClassAssignmentRepository $classAssignmentRepository,
        private ClassRepository $classRepository,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): StudentResource
    {
        if (!$this->authorizationChecker->isGranted(StudentVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à consulter les élèves.');
        }

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

        /** @var string $studentId */
        $studentId = $uriVariables['id'] ?? '';
        $tenantId = $this->tenantContext->getCurrentTenantId();

        $user = $this->userRepository->findById(UserId::fromString($studentId));

        if ($user === null || (string) $user->tenantId !== (string) $tenantId || !$user->aLeRole(Role::ELEVE)) {
            throw new NotFoundHttpException('Élève non trouvé.');
        }

        $resource = new StudentResource();
        $resource->id = (string) $user->id;
        $resource->firstName = $user->firstName;
        $resource->lastName = $user->lastName;
        $resource->email = $user->email !== null ? (string) $user->email : null;
        $resource->statut = $user->statut->value;
        $resource->studentNumber = $user->studentNumber;
        $resource->dateNaissance = $user->dateNaissance?->format('Y-m-d');

        // Look up class assignment
        $academicYearId = $this->academicYearResolver->resolve('current');

        if ($academicYearId !== null) {
            $assignment = $this->classAssignmentRepository->findByStudent(
                $user->id,
                AcademicYearId::fromString($academicYearId),
                TenantId::fromString((string) $tenantId),
            );

            if ($assignment !== null) {
                $resource->classId = (string) $assignment->classId;

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

                if ($class !== null) {
                    $resource->className = (string) $class->name;
                    $resource->classLevel = $class->level?->value;
                }
            }
        }

        return $resource;
    }
}
