<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Query\GetAssignmentsForTeacher\GetAssignmentsForTeacherHandler;
use App\Administration\Application\Query\GetAssignmentsForTeacher\GetAssignmentsForTeacherQuery;
use App\Administration\Infrastructure\Api\Resource\TeacherAssignmentResource;
use App\Administration\Infrastructure\Security\TeacherAssignmentVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use Override;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProviderInterface<TeacherAssignmentResource>
 */
final readonly class TeacherAssignmentsByTeacherProvider implements ProviderInterface
{
    public function __construct(
        private GetAssignmentsForTeacherHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

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

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

        // Passer une ressource avec le teacherId pour que le voter puisse
        // vérifier que l'enseignant ne consulte que ses propres affectations.
        $subjectForVoter = new TeacherAssignmentResource();
        $subjectForVoter->teacherId = $teacherId;

        if (!$this->authorizationChecker->isGranted(TeacherAssignmentVoter::VIEW, $subjectForVoter)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir les affectations.');
        }
        $tenantId = (string) $this->tenantContext->getCurrentTenantId();

        try {
            $query = new GetAssignmentsForTeacherQuery(
                teacherId: $teacherId,
                tenantId: $tenantId,
            );

            $dtos = ($this->handler)($query);

            return array_map(TeacherAssignmentResource::fromDto(...), $dtos);
        } catch (InvalidUuidStringException $e) {
            throw new BadRequestHttpException('Identifiant enseignant invalide.', $e);
        }
    }
}
