<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Api\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Scolarite\Application\Command\EndReplacement\EndReplacementCommand;
use App\Scolarite\Application\Command\EndReplacement\EndReplacementHandler;
use App\Scolarite\Domain\Exception\RemplacementDejaTermineException;
use App\Scolarite\Domain\Exception\RemplacementNotFoundException;
use App\Scolarite\Infrastructure\Api\Resource\TeacherReplacementResource;
use App\Scolarite\Infrastructure\Security\TeacherReplacementVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProcessorInterface<TeacherReplacementResource, null>
 */
final readonly class EndTeacherReplacementProcessor implements ProcessorInterface
{
    public function __construct(
        private EndReplacementHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    #[Override]
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): null
    {
        if (!$this->authorizationChecker->isGranted(TeacherReplacementVoter::DELETE)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à terminer un remplacement.');
        }

        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        /** @var string $id */
        $id = $uriVariables['id'];

        try {
            ($this->handler)(new EndReplacementCommand(
                replacementId: $id,
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
            ));
        } catch (RemplacementNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (RemplacementDejaTermineException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        return null;
    }
}
