<?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\DeleteAppreciationTemplate\DeleteAppreciationTemplateCommand;
use App\Scolarite\Application\Command\DeleteAppreciationTemplate\DeleteAppreciationTemplateHandler;
use App\Scolarite\Domain\Exception\AppreciationTemplateNonTrouveeException;
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\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

/**
 * @implements ProcessorInterface<AppreciationTemplateResource, null>
 */
final readonly class DeleteAppreciationTemplateProcessor implements ProcessorInterface
{
    public function __construct(
        private DeleteAppreciationTemplateHandler $handler,
        private TenantContext $tenantContext,
        private Security $security,
    ) {
    }

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

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

            return null;
        } catch (AppreciationTemplateNonTrouveeException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (NonProprietaireDuModeleException $e) {
            throw new AccessDeniedHttpException($e->getMessage());
        }
    }
}
