<?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\CreateHomeworkWithException\CreateHomeworkWithExceptionCommand;
use App\Scolarite\Application\Command\CreateHomeworkWithException\CreateHomeworkWithExceptionHandler;
use App\Scolarite\Domain\Exception\DateEcheanceInvalideException;
use App\Scolarite\Domain\Exception\EnseignantNonAffecteException;
use App\Scolarite\Domain\Exception\ExceptionNonNecessaireException;
use App\Scolarite\Domain\Exception\JustificationTropCourteException;
use App\Scolarite\Infrastructure\Api\Resource\HomeworkExceptionResource;
use App\Scolarite\Infrastructure\Api\Resource\HomeworkResource;
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<HomeworkExceptionResource, HomeworkResource>
 */
final readonly class CreateHomeworkWithExceptionProcessor implements ProcessorInterface
{
    public function __construct(
        private CreateHomeworkWithExceptionHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private Security $security,
    ) {
    }

    /**
     * @param HomeworkExceptionResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): HomeworkResource
    {
        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 CreateHomeworkWithExceptionCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                classId: $data->classId ?? '',
                subjectId: $data->subjectId ?? '',
                teacherId: $user->userId(),
                title: $data->title ?? '',
                description: $data->description,
                dueDate: $data->dueDate ?? '',
                justification: $data->justification ?? '',
                ruleTypes: $data->ruleTypes ?? [],
            );

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

            $homework = $result['homework'];
            $exception = $result['exception'];

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

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

            return HomeworkResource::fromDomain(
                $homework,
                ruleException: $exception,
            );
        } catch (ExceptionNonNecessaireException|JustificationTropCourteException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (EnseignantNonAffecteException|DateEcheanceInvalideException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (InvalidUuidStringException $e) {
            throw new BadRequestHttpException('UUID invalide : ' . $e->getMessage());
        }
    }
}
