<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Application\Command\ConfigureGradingMode\ConfigureGradingModeCommand;
use App\Administration\Application\Command\ConfigureGradingMode\ConfigureGradingModeHandler;
use App\Administration\Application\Port\GradeExistenceChecker;
use App\Administration\Domain\Exception\CannotChangeGradingModeWithExistingGradesException;
use App\Administration\Domain\Model\SchoolClass\AcademicYearId;
use App\Administration\Domain\Model\SchoolClass\SchoolId;
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\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use ValueError;

/**
 * Processor API Platform pour configurer le mode de notation.
 *
 * @implements ProcessorInterface<GradingModeResource, GradingModeResource>
 */
final readonly class ConfigureGradingModeProcessor implements ProcessorInterface
{
    public function __construct(
        private ConfigureGradingModeHandler $handler,
        private GradeExistenceChecker $gradeExistenceChecker,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
        private SchoolIdResolver $schoolIdResolver,
    ) {
    }

    /**
     * @param GradingModeResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): GradingModeResource
    {
        if (!$this->authorizationChecker->isGranted(GradingModeVoter::CONFIGURE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à configurer le mode de notation.');
        }

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

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

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

        $schoolId = $this->schoolIdResolver->resolveForTenant($tenantId);

        try {
            $command = new ConfigureGradingModeCommand(
                tenantId: $tenantId,
                schoolId: $schoolId,
                academicYearId: $academicYearId,
                gradingMode: $data->mode ?? '',
            );

            $configuration = ($this->handler)($command);

            foreach ($configuration->pullDomainEvents() as $event) {
                $this->eventBus->dispatch($event);
            }

            $resource = GradingModeResource::fromDomain($configuration);
            $resource->hasExistingGrades = $this->gradeExistenceChecker->hasGradesForYear(
                TenantId::fromString($tenantId),
                SchoolId::fromString($schoolId),
                AcademicYearId::fromString($academicYearId),
            );
            $resource->availableModes = GradingModeResource::allAvailableModes();

            return $resource;
        } catch (CannotChangeGradingModeWithExistingGradesException $e) {
            throw new ConflictHttpException($e->getMessage());
        } catch (ValueError $e) {
            throw new BadRequestHttpException('Mode de notation invalide : ' . $e->getMessage());
        }
    }
}
