<?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\SaveAppreciation\SaveAppreciationCommand;
use App\Scolarite\Application\Command\SaveAppreciation\SaveAppreciationHandler;
use App\Scolarite\Domain\Exception\AppreciationTropLongueException;
use App\Scolarite\Domain\Exception\GradeNotFoundException;
use App\Scolarite\Domain\Exception\NonProprietaireDeLEvaluationException;
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\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProcessorInterface<GradeResource, GradeResource>
 */
final readonly class SaveAppreciationProcessor implements ProcessorInterface
{
    public function __construct(
        private SaveAppreciationHandler $handler,
        private TenantContext $tenantContext,
        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 $gradeId */
        $gradeId = $uriVariables['id'] ?? '';

        try {
            $command = new SaveAppreciationCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                gradeId: $gradeId,
                teacherId: $user->userId(),
                appreciation: $data->appreciation,
            );

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

            return GradeResource::fromDomain($grade);
        } catch (NonProprietaireDeLEvaluationException $e) {
            throw new AccessDeniedHttpException($e->getMessage());
        } catch (GradeNotFoundException) {
            throw new NotFoundHttpException('Aucune note trouvée. Veuillez d\'abord saisir une note pour cet élève avant d\'ajouter une appréciation.');
        } catch (AppreciationTropLongueException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
