<?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\PublishGrades\PublishGradesCommand;
use App\Scolarite\Application\Command\PublishGrades\PublishGradesHandler;
use App\Scolarite\Domain\Exception\AucuneNoteSaisieException;
use App\Scolarite\Domain\Exception\NonProprietaireDeLEvaluationException;
use App\Scolarite\Domain\Exception\NotesDejaPublieesException;
use App\Scolarite\Infrastructure\Api\Resource\GradeResource;
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\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;

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

    /**
     * @param GradeResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): GradeResource
    {
        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 PublishGradesCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                evaluationId: $evaluationId,
                teacherId: $user->userId(),
            );

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

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

            $resource = new GradeResource();
            $resource->id = (string) $evaluation->id;
            $resource->evaluationId = (string) $evaluation->id;
            $resource->published = true;
            $resource->gradesPublishedAt = $evaluation->gradesPublishedAt;

            return $resource;
        } catch (NonProprietaireDeLEvaluationException $e) {
            throw new AccessDeniedHttpException($e->getMessage());
        } catch (NotesDejaPublieesException|AucuneNoteSaisieException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
