<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Application\Command\SaveGrades\SaveGradesCommand;
use App\Scolarite\Application\Command\SaveGrades\SaveGradesHandler;
use App\Scolarite\Domain\Exception\NonProprietaireDeLEvaluationException;
use App\Scolarite\Domain\Exception\NoteRequiseException;
use App\Scolarite\Domain\Exception\ValeurNoteInvalideException;
use App\Scolarite\Infrastructure\Api\Resource\GradeResource;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;

/**
 * @implements ProcessorInterface<GradeResource, array<GradeResource>>
 */
final readonly class SaveGradesProcessor implements ProcessorInterface
{
    public function __construct(
        private SaveGradesHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private Security $security,
    ) {
    }

    /**
     * @param GradeResource $data
     *
     * @return array<GradeResource>
     */
    #[Override]
    public function process(mixed $data, 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.');
        }

        /** @var string $evaluationId */
        $evaluationId = $uriVariables['evaluationId'] ?? '';

        try {
            $command = new SaveGradesCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                evaluationId: $evaluationId,
                teacherId: $user->userId(),
                grades: $data->grades ?? [],
            );

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

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

            return array_map(
                static fn ($grade) => GradeResource::fromDomain($grade),
                $savedGrades,
            );
        } catch (NonProprietaireDeLEvaluationException $e) {
            throw new AccessDeniedHttpException($e->getMessage());
        } catch (ValeurNoteInvalideException|NoteRequiseException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
