<?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\UpdateAppreciationTemplate\UpdateAppreciationTemplateCommand;
use App\Scolarite\Application\Command\UpdateAppreciationTemplate\UpdateAppreciationTemplateHandler;
use App\Scolarite\Domain\Exception\AppreciationTemplateNonTrouveeException;
use App\Scolarite\Domain\Exception\CategorieAppreciationInvalideException;
use App\Scolarite\Domain\Exception\NonProprietaireDuModeleException;
use App\Scolarite\Infrastructure\Api\Resource\AppreciationTemplateResource;
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<AppreciationTemplateResource, AppreciationTemplateResource>
 */
final readonly class UpdateAppreciationTemplateProcessor implements ProcessorInterface
{
    public function __construct(
        private UpdateAppreciationTemplateHandler $handler,
        private TenantContext $tenantContext,
        private Security $security,
    ) {
    }

    /**
     * @param AppreciationTemplateResource $data
     */
    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): AppreciationTemplateResource
    {
        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 $templateId */
        $templateId = $uriVariables['id'] ?? '';

        try {
            $command = new UpdateAppreciationTemplateCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                teacherId: $user->userId(),
                templateId: $templateId,
                title: $data->title ?? '',
                content: $data->content ?? '',
                category: $data->category,
            );

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

            return AppreciationTemplateResource::fromDomain($template);
        } catch (AppreciationTemplateNonTrouveeException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (NonProprietaireDuModeleException $e) {
            throw new AccessDeniedHttpException($e->getMessage());
        } catch (CategorieAppreciationInvalideException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
