<?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\CreateEvaluation\CreateEvaluationCommand;
use App\Scolarite\Application\Command\CreateEvaluation\CreateEvaluationHandler;
use App\Scolarite\Domain\Exception\BaremeInvalideException;
use App\Scolarite\Domain\Exception\CoefficientInvalideException;
use App\Scolarite\Domain\Exception\EnseignantNonAffecteException;
use App\Scolarite\Infrastructure\Api\Resource\EvaluationResource;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;

/**
 * @implements ProcessorInterface<EvaluationResource, EvaluationResource>
 */
final readonly class CreateEvaluationProcessor implements ProcessorInterface
{
    public function __construct(
        private CreateEvaluationHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private Security $security,
    ) {
    }

    /**
     * @param EvaluationResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): EvaluationResource
    {
        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.');
        }

        try {
            $command = new CreateEvaluationCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                classId: $data->classId ?? '',
                subjectId: $data->subjectId ?? '',
                teacherId: $user->userId(),
                title: $data->title ?? '',
                description: $data->description,
                evaluationDate: $data->evaluationDate ?? '',
                gradeScale: $data->gradeScale ?? 20,
                coefficient: $data->coefficient ?? 1.0,
            );

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

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

            return EvaluationResource::fromDomain($evaluation);
        } catch (EnseignantNonAffecteException|BaremeInvalideException|CoefficientInvalideException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (InvalidUuidStringException $e) {
            throw new BadRequestHttpException('UUID invalide : ' . $e->getMessage());
        }
    }
}
