<?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\Application\Query\GetReplacedClassesForTeacher\GetReplacedClassesForTeacherHandler;
use App\Scolarite\Application\Query\GetReplacedClassesForTeacher\GetReplacedClassesForTeacherQuery;
use App\Scolarite\Infrastructure\Api\Resource\ReplacedClassResource;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * Fournit les classes du remplaçant connecté (GET /api/me/replaced-classes).
 *
 * @implements ProviderInterface<ReplacedClassResource>
 */
final readonly class ReplacedClassesProvider implements ProviderInterface
{
    public function __construct(
        private GetReplacedClassesForTeacherHandler $handler,
        private TenantContext $tenantContext,
        private Security $security,
    ) {
    }

    /** @return array<ReplacedClassResource> */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        $user = $this->security->getUser();

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

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

        $query = new GetReplacedClassesForTeacherQuery(
            replacementTeacherId: $user->userId(),
            tenantId: (string) $this->tenantContext->getCurrentTenantId(),
        );

        return array_map(
            ReplacedClassResource::fromDto(...),
            ($this->handler)($query),
        );
    }
}
