<?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\Domain\Model\Competency\CompetencyLevel;
use App\Scolarite\Domain\Repository\CustomCompetencyLevelRepository;
use App\Scolarite\Infrastructure\Api\Resource\CompetencyLevelResource;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProviderInterface<CompetencyLevelResource>
 */
final readonly class CompetencyLevelCollectionProvider implements ProviderInterface
{
    public function __construct(
        private CustomCompetencyLevelRepository $customLevelRepository,
        private TenantContext $tenantContext,
        private Security $security,
    ) {
    }

    /** @return array<CompetencyLevelResource> */
    #[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();

        // Utiliser les niveaux personnalisés si définis, sinon les niveaux standards
        $customLevels = $this->customLevelRepository->findByTenant($tenantId);

        if ($customLevels !== []) {
            $resources = [];
            foreach ($customLevels as $level) {
                $resource = new CompetencyLevelResource();
                $resource->code = $level->code;
                $resource->name = $level->name;
                $resource->color = $level->color;
                $resource->sortOrder = $level->sortOrder;
                $resources[] = $resource;
            }

            return $resources;
        }

        // Niveaux standards par défaut
        $resources = [];
        foreach (CompetencyLevel::cases() as $level) {
            $resource = new CompetencyLevelResource();
            $resource->code = $level->value;
            $resource->name = $level->label();
            $resource->color = $level->color();
            $resource->sortOrder = $level->sortOrder();
            $resources[] = $resource;
        }

        return $resources;
    }
}
