<?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\CreateAppreciationTemplate\CreateAppreciationTemplateCommand;
use App\Scolarite\Application\Command\CreateAppreciationTemplate\CreateAppreciationTemplateHandler;
use App\Scolarite\Domain\Exception\CategorieAppreciationInvalideException;
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\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProcessorInterface<AppreciationTemplateResource, AppreciationTemplateResource>
 */
final readonly class CreateAppreciationTemplateProcessor implements ProcessorInterface
{
    public function __construct(
        private CreateAppreciationTemplateHandler $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.');
        }

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

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

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