<?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\LinkCompetenciesToEvaluation\LinkCompetenciesToEvaluationCommand;
use App\Scolarite\Application\Command\LinkCompetenciesToEvaluation\LinkCompetenciesToEvaluationHandler;
use App\Scolarite\Domain\Exception\EvaluationNotFoundException;
use App\Scolarite\Domain\Exception\NonProprietaireDeLEvaluationException;
use App\Scolarite\Infrastructure\Api\Resource\CompetencyEvaluationResource;
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;

/**
 * @implements ProcessorInterface<CompetencyEvaluationResource, array<CompetencyEvaluationResource>>
 */
final readonly class LinkCompetenciesToEvaluationProcessor implements ProcessorInterface
{
    public function __construct(
        private LinkCompetenciesToEvaluationHandler $handler,
        private TenantContext $tenantContext,
        private Security $security,
    ) {
    }

    /**
     * @param CompetencyEvaluationResource $data
     *
     * @return array<CompetencyEvaluationResource>
     */
    #[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 LinkCompetenciesToEvaluationCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                evaluationId: $evaluationId,
                teacherId: $user->userId(),
                competencyIds: $data->competencyIds ?? [],
            );

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

            return array_map(static function ($ce): CompetencyEvaluationResource {
                $resource = new CompetencyEvaluationResource();
                $resource->id = (string) $ce->id;
                $resource->evaluationId = (string) $ce->evaluationId;
                $resource->competencyId = (string) $ce->competencyId;

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