<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Query\GetTeachersForClass\GetTeachersForClassHandler;
use App\Administration\Application\Query\GetTeachersForClass\GetTeachersForClassQuery;
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 TeacherAssignmentsByClassProvider implements ProviderInterface
{
    public function __construct(
        private GetTeachersForClassHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    /**
     * @return TeacherAssignmentResource[]
     */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        if (!$this->authorizationChecker->isGranted(TeacherAssignmentVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir les enseignants de cette classe.');
        }

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

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

        try {
            $query = new GetTeachersForClassQuery(
                classId: $classId,
                tenantId: $tenantId,
            );

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

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