<?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\CreateHomework\CreateHomeworkCommand;
use App\Scolarite\Application\Command\CreateHomework\CreateHomeworkHandler;
use App\Scolarite\Domain\Exception\DateEcheanceInvalideException;
use App\Scolarite\Domain\Exception\EnseignantNonAffecteException;
use App\Scolarite\Domain\Exception\ReglesDevoirsNonRespecteesException;
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\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;

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

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

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

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

            return HomeworkResource::fromDomain($homework);
        } catch (ReglesDevoirsNonRespecteesException $e) {
            if ($e->bloquant) {
                return new JsonResponse([
                    'type' => 'homework_rules_blocked',
                    'message' => $e->getMessage(),
                    'warnings' => $e->warnings,
                    'suggestedDates' => $e->suggestedDates,
                    'exceptionRequestPath' => '/dashboard/teacher/homework/request-exception',
                ], Response::HTTP_UNPROCESSABLE_ENTITY);
            }

            return new JsonResponse([
                'type' => 'homework_rules_warning',
                'message' => $e->getMessage(),
                'warnings' => $e->warnings,
            ], Response::HTTP_CONFLICT);
        } catch (EnseignantNonAffecteException|DateEcheanceInvalideException $e) {
            throw new BadRequestHttpException($e->getMessage());
        } catch (InvalidUuidStringException $e) {
            throw new BadRequestHttpException('UUID invalide : ' . $e->getMessage());
        }
    }
}
