<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Port\GradeExistenceChecker;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Model\SchoolClass\SchoolId;
use App\Administration\Domain\Repository\GradingConfigurationRepository;
use App\Administration\Infrastructure\Api\Resource\GradingModeResource;
use App\Administration\Infrastructure\School\SchoolIdResolver;
use App\Administration\Infrastructure\Security\GradingModeVoter;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Shared\Domain\Tenant\TenantId;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * State Provider pour récupérer la configuration du mode de notation.
 *
 * @implements ProviderInterface<GradingModeResource>
 */
final readonly class GradingModeProvider implements ProviderInterface
{
    public function __construct(
        private GradingConfigurationRepository $repository,
        private GradeExistenceChecker $gradeExistenceChecker,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
        private SchoolIdResolver $schoolIdResolver,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): GradingModeResource
    {
        if (!$this->authorizationChecker->isGranted(GradingModeVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir la configuration de notation.');
        }

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

        $tenantIdStr = (string) $this->tenantContext->getCurrentTenantId();
        $tenantId = TenantId::fromString($tenantIdStr);
        /** @var string $rawAcademicYearId */
        $rawAcademicYearId = $uriVariables['academicYearId'];

        $resolvedYearId = $this->academicYearResolver->resolve($rawAcademicYearId);
        if ($resolvedYearId === null) {
            throw new NotFoundHttpException('Année scolaire non trouvée.');
        }

        $academicYearId = AcademicYearId::fromString($resolvedYearId);
        $schoolId = SchoolId::fromString($this->schoolIdResolver->resolveForTenant($tenantIdStr));

        $config = $this->repository->findBySchoolAndYear(
            $tenantId,
            $schoolId,
            $academicYearId,
        );

        if ($config === null) {
            $resource = GradingModeResource::defaultForYear($resolvedYearId);
        } else {
            $resource = GradingModeResource::fromDomain($config);
        }

        $resource->hasExistingGrades = $this->gradeExistenceChecker->hasGradesForYear(
            $tenantId,
            $schoolId,
            $academicYearId,
        );
        $resource->availableModes = GradingModeResource::allAvailableModes();

        return $resource;
    }
}
