<?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\SaveCompetencyResults\SaveCompetencyResultsCommand;
use App\Scolarite\Application\Command\SaveCompetencyResults\SaveCompetencyResultsHandler;
use App\Scolarite\Domain\Exception\EvaluationNotFoundException;
use App\Scolarite\Domain\Exception\NonProprietaireDeLEvaluationException;
use App\Scolarite\Infrastructure\Api\Resource\CompetencyResultResource;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use DomainException;
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<CompetencyResultResource, array<CompetencyResultResource>>
 */
final readonly class SaveCompetencyResultsProcessor implements ProcessorInterface
{
    public function __construct(
        private SaveCompetencyResultsHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private Security $security,
    ) {
    }

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

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

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

            return array_map(static function ($result) use ($evaluationId): CompetencyResultResource {
                $resource = new CompetencyResultResource();
                $resource->id = (string) $result->id;
                $resource->evaluationId = $evaluationId;
                $resource->competencyEvaluationId = (string) $result->competencyEvaluationId;
                $resource->studentId = (string) $result->studentId;
                $resource->levelCode = $result->levelCode;

                return $resource;
            }, $savedResults);
        } catch (EvaluationNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (NonProprietaireDeLEvaluationException $e) {
            throw new AccessDeniedHttpException($e->getMessage());
        } catch (DomainException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
