<?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\DeleteHomework\DeleteHomeworkCommand;
use App\Scolarite\Application\Command\DeleteHomework\DeleteHomeworkHandler;
use App\Scolarite\Domain\Exception\DevoirDejaSupprimeException;
use App\Scolarite\Domain\Exception\HomeworkNotFoundException;
use App\Scolarite\Domain\Exception\NonProprietaireDuDevoirException;
use App\Scolarite\Infrastructure\Api\Resource\HomeworkResource;
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;
use Symfony\Component\Messenger\MessageBusInterface;

/**
 * @implements ProcessorInterface<HomeworkResource, HomeworkResource>
 */
final readonly class DeleteHomeworkProcessor implements ProcessorInterface
{
    public function __construct(
        private DeleteHomeworkHandler $handler,
        private TenantContext $tenantContext,
        private MessageBusInterface $eventBus,
        private Security $security,
    ) {
    }

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

        try {
            $command = new DeleteHomeworkCommand(
                tenantId: (string) $this->tenantContext->getCurrentTenantId(),
                homeworkId: $id,
                teacherId: $user->userId(),
            );

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

            foreach ($homework->pullDomainEvents() as $event) {
                $this->eventBus->dispatch($event);
            }

            return HomeworkResource::fromDomain($homework);
        } catch (HomeworkNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        } catch (NonProprietaireDuDevoirException $e) {
            throw new AccessDeniedHttpException($e->getMessage());
        } catch (DevoirDejaSupprimeException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
    }
}
