<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Query\GetClasses\GetClassesHandler;
use App\Administration\Application\Query\GetClasses\GetClassesQuery;
use App\Administration\Infrastructure\Api\Resource\ClassResource;
use App\Administration\Infrastructure\Security\ClassVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Ramsey\Uuid\Uuid;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * State Provider pour récupérer la liste des classes.
 *
 * @implements ProviderInterface<ClassResource>
 */
final readonly class ClassCollectionProvider implements ProviderInterface
{
    public function __construct(
        private GetClassesHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    /**
     * @return ClassResource[]
     */
    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        // Vérifier les permissions de lecture (sans sujet spécifique)
        if (!$this->authorizationChecker->isGranted(ClassVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir les classes.');
        }

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

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();

        // TODO: Récupérer academic_year_id depuis le contexte utilisateur
        // quand le module AcademicYears sera implémenté.
        $academicYearId = Uuid::uuid5(Uuid::NAMESPACE_DNS, "academic-year-2024-2025-{$tenantId}")->toString();

        $query = new GetClassesQuery(
            tenantId: $tenantId,
            academicYearId: $academicYearId,
        );

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

        return array_map(
            static function ($dto) {
                $resource = new ClassResource();
                $resource->id = $dto->id;
                $resource->name = $dto->name;
                $resource->level = $dto->level;
                $resource->capacity = $dto->capacity;
                $resource->description = $dto->description;
                $resource->status = $dto->status;
                $resource->createdAt = $dto->createdAt;
                $resource->updatedAt = $dto->updatedAt;

                return $resource;
            },
            $classDtos,
        );
    }
}
