<?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\DeleteEvaluation\DeleteEvaluationCommand;
use App\Scolarite\Application\Command\DeleteEvaluation\DeleteEvaluationHandler;
use App\Scolarite\Domain\Exception\EvaluationDejaSupprimeeException;
use App\Scolarite\Domain\Exception\EvaluationNotFoundException;
use App\Scolarite\Domain\Exception\NonProprietaireDeLEvaluationException;
use App\Scolarite\Infrastructure\Api\Resource\EvaluationResource;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;

/**
 * @implements ProcessorInterface<EvaluationResource, EvaluationResource>
 */
final readonly class DeleteEvaluationProcessor implements ProcessorInterface
{
    public function __construct(
        private DeleteEvaluationHandler $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.');
        }

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

        try {
            $command = new DeleteEvaluationCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                evaluationId: $id,
                teacherId: $user->userId(),
            );

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

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

            return EvaluationResource::fromDomain($evaluation);
        } catch (EvaluationNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (NonProprietaireDeLEvaluationException $e) {
            throw new AccessDeniedHttpException($e->getMessage());
        } catch (EvaluationDejaSupprimeeException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
