<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Domain\Repository\AppreciationTemplateRepository;
use App\Scolarite\Infrastructure\Api\Resource\AppreciationTemplateResource;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProviderInterface<AppreciationTemplateResource>
 */
final readonly class AppreciationTemplateCollectionProvider implements ProviderInterface
{
    public function __construct(
        private AppreciationTemplateRepository $templateRepository,
        private TenantContext $tenantContext,
        private Security $security,
    ) {
    }

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

        $tenantId = $this->tenantContext->getCurrentTenantId();
        $teacherId = UserId::fromString($user->userId());

        $templates = $this->templateRepository->findByTeacher($teacherId, $tenantId);

        return array_map(
            static fn ($template) => AppreciationTemplateResource::fromDomain($template),
            $templates,
        );
    }
}
